You need to also get weapons:
struct AnyWeapon: Weapon { private let _fire: () -> Void func fire() { _fire() } init<W: Weapon>(_ weapon: W) { _fire = weapon.fire } }
However, AnySoldier
does not have to be shared.
struct AnySoldier : Soldier { private let _fight: () -> Void let weapon: AnyWeapon init<S: Soldier>(_ soldier: S) { _fight = soldier.fight weapon = AnyWeapon(soldier.weapon) } func fight() { _fight() } }
Do not lose sight of another approach, which is to replace the Weapon with a simple function and make the Soldier a simple structure. For instance:
struct Soldier { private let weaponFire: () -> Void func fight() { weaponFire() } static let sniper = Soldier(weaponFire: { print("Bullets away!") }) } let sniper = Soldier.sniper sniper.fight()
I discuss some of these later in Beyond Crusty: Real-World Protocols . Sometimes you donβt need a protocol.
source share