Jacob233
Jacob233

Reputation: 312

Pass subclass of the class as a parameter in other class Swift

i have three classes, class A:

class Game {
    init(tactic:Tactic) {
        //Set tactic
        tacticReference = tactic
        setShipsMapAndShotsMap()
    }
}

Class B:

class Tactic {
    var name:String?

    init() {
        name = "Default"
    }

   func shotPosition(shots: inout [[Int]],shipMap:[[Int]],ships:[Ship]) -> [Int] {
        return []
   }
}

And subclass of class B:

    class RandomTactic:Tactic {
override init() {
    super.init()
    name = "RandomTactic"
}

override func shotPosition( shots: inout [[Int]], shipMap: [[Int]], ships: [Ship]) -> [Int] {
    //Position
    var vertical:Int?
    var horizontal:Int?

    //Random position
    repeat{
        horizontal = Int(arc4random_uniform(10))
        vertical = Int(arc4random_uniform(10))
    }while shots[vertical!][horizontal!] != 0

    //Fire at the position
    shots[vertical!][horizontal!] += 1

    return [vertical!,horizontal!]
}   
}

And I want to create Game object with class C instance as init parameter like that let game = Game(tactic: RandomTactic) but Xcode give me an error Cannot convert value of type 'RandomTactic' to expected argument of type 'Tactic'. I want to create ships game and test a lot of different tactics so I have to do it like that, is there any solution?

Upvotes: 0

Views: 623

Answers (1)

Lorenzo B
Lorenzo B

Reputation: 33428

Try using RandomTactic() and not simply RandomTactic. In fact you want to inject an instance of a class that extends Tactic.

Anyway, I would create Tactic as a protocol instead of a class, since it's act as an abstract class (concept that Swift does not have).

Upvotes: 1

Related Questions