SEEEEEAAAAAA10000000

Opaque Types

Oct 6th, 2021 (edited)
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.42 KB | None | 0 0
  1. protocol Advance {
  2.     associatedtype Element
  3.     mutating func next() -> Element
  4. }
  5.  
  6.  
  7. struct Cylinder<Cartridge>: Advance {
  8.     var array: [Cartridge]
  9.     mutating func next() -> Cartridge {
  10.         array.removeLast()
  11.     }
  12. }
  13.  
  14. struct Bullet {}
  15. struct GunpowderChip {
  16.     let bullet: Bullet
  17. }
  18.  
  19. struct MachineGunExplicit<B> {
  20.     var clip: Cylinder<B>
  21.     mutating func fire() -> B {
  22.         clip.next()
  23.     }
  24. }
  25.  
  26. protocol Gun {
  27.     associatedtype Bullet
  28.     mutating func fire() -> Bullet
  29. }
  30.  
  31. struct MachineGunImplicit<C: Advance> : Gun {
  32.     var clip: C
  33.     mutating func fire() -> C.Element {
  34.         clip.next()
  35.     }
  36. }
  37.  
  38. struct CraftBench {
  39.     func makeSomeAdvane() -> some Advance {
  40.         let bullets = Array(repeating: Bullet(), count: 20)
  41.         let clip = Cylinder(array: bullets)
  42.         return clip
  43.     }
  44.     func makeSomeGun() -> some Gun {
  45.         let clip = makeSomeAdvane()
  46.         let gun = MachineGunImplicit(clip: clip)
  47.         return gun
  48.     }
  49. }
  50.  
  51. struct ShootingRange {
  52.    
  53.    
  54.     func run() {
  55.         var gun = CraftBench().makeSomeGun()
  56.         (0...10).forEach { _ in
  57.             let b = gun.fire() // the b has wonderful type 'let b: (some Gun).Bullet'
  58.             print(b)
  59.         }
  60.     }
  61.    
  62. }
  63. /*
  64. Bullet()
  65. Bullet()
  66. Bullet()
  67. Bullet()
  68. Bullet()
  69. Bullet()
  70. Bullet()
  71. Bullet()
  72. Bullet()
  73. Bullet()
  74. Bullet()
  75. Compiler knows that underlying type of 'b' is the Bullet.
  76. */
Add Comment
Please, Sign In to add comment