0

so I have this code, I have a soldier that implement Pawn and have default implementation of possible moves, and I have an ASoldier that do the same. I wanna make another soldier called superSolider that has the Soldier and Asoldier possible moves.

how should I build it, because that way I cant reach to the default implementation

struct PosibleMove {
    let x: Int
    let y: Int
}

protocol Pawn {
    func posibleMoves() -> [PosibleMove]
}

protocol Soldier: Pawn {
    func shot()
}

extension Soldier {
    func posibleMoves() -> [PosibleMove] {
        return [PosibleMove(x: 0, y: 0), PosibleMove(x: 1, y: 1)]
    }
}

protocol ASoldier: Pawn {
    func aShot()
}

extension ASoldier {
    func posibleMoves() -> [PosibleMove] {
         return [PosibleMove(x: 2, y: 2), PosibleMove(x: 3, y: 3)]
     }
}

protocol SuperSoldier: ASoldier, Soldier {
    
}

extension SuperSoldier {
    func posibleMoves() -> [PosibleMove] {
        // here I would like to use ASoldier.posibleMoves() + Soldier.posibleMoves()
    }
}

let pawns = [[Pawn]]()

func checkPosibleMoves(x: Int, y: Int) -> [PosibleMove] {
    return pawns[x][y].posibleMoves()
}
TalBenAsulo
  • 131
  • 6
  • Does this answer your question? [Calling protocol default implementation from regular method](https://stackoverflow.com/questions/32602712/calling-protocol-default-implementation-from-regular-method) – zrzka Jul 28 '20 at 12:15
  • Check the duplicate question I used in the close vote. You have to a) remove `posibleMoves` function from the `Pawn` protocol, b) add default implementation via `Pawn` extension (& return `[]`), c) use `(self as ASoldier).posibleMoves() + (self as Soldier).posibleMoves()` in the `SuperSoldier`'s `posibleMoves`, d) use `Set` so you can union, intersect, ... possible moves. Time to re-think your design? – zrzka Jul 28 '20 at 12:21
  • so casting is the only way, maybe there is a better architecture to use? – TalBenAsulo Jul 29 '20 at 12:29

0 Answers0