Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- protocol Advance {
- associatedtype Element
- mutating func next() -> Element
- }
- struct Cylinder<Cartridge>: Advance {
- var array: [Cartridge]
- mutating func next() -> Cartridge {
- array.removeLast()
- }
- }
- struct Bullet {}
- struct GunpowderChip {
- let bullet: Bullet
- }
- struct MachineGunExplicit<B> {
- var clip: Cylinder<B>
- mutating func fire() -> B {
- clip.next()
- }
- }
- protocol Gun {
- associatedtype Bullet
- mutating func fire() -> Bullet
- }
- struct MachineGunImplicit<C: Advance> : Gun {
- var clip: C
- mutating func fire() -> C.Element {
- clip.next()
- }
- }
- struct CraftBench {
- func makeSomeAdvane() -> some Advance {
- let bullets = Array(repeating: Bullet(), count: 20)
- let clip = Cylinder(array: bullets)
- return clip
- }
- func makeSomeGun() -> some Gun {
- let clip = makeSomeAdvane()
- let gun = MachineGunImplicit(clip: clip)
- return gun
- }
- }
- struct ShootingRange {
- func run() {
- var gun = CraftBench().makeSomeGun()
- (0...10).forEach { _ in
- let b = gun.fire() // the b has wonderful type 'let b: (some Gun).Bullet'
- print(b)
- }
- }
- }
- /*
- Bullet()
- Bullet()
- Bullet()
- Bullet()
- Bullet()
- Bullet()
- Bullet()
- Bullet()
- Bullet()
- Bullet()
- Bullet()
- Compiler knows that underlying type of 'b' is the Bullet.
- */
Add Comment
Please, Sign In to add comment