协议和初始化参数

Protocol and init argument

一位前同事留下了一个未完成且未记录的游戏。

在阅读他的代码时我发现:

protocol EnemyMovement {
    func forward(speedPercent: Int)
    func reverse(speedPercent: Int)
    func left(speedPercent: Int)
    func right(speedPercent: Int)
}

protocol Enemy {
    var name: String {get set}
    var enemyMovement: EnemyMovement {get set}

    init (name: String, enemyMovement: EnemyMovement)
}

class EnemyInstance: Enemy {
    var name = "No enemy Name"
    var enemyMovement: EnemyMovement

    required init (name: String, enemyMovement: EnemyMovement) {
        self.name = name
        self.enemyMovement = enemyMovement
//...
}

我找不到 EnemyInstance 的具体实例,但如果很清楚如何传递名称字符串,我不明白应该如何传递 EnemyMovement。

var enemy = EnemyInstance(name: "zombie", enemyMovement?...)

有什么想法吗?

由于参数必须是符合EnemyMovement的类型,包括这些方法,你必须传递这个对象。因此,您可以尝试创建示例 struct

struct Movements: EnemyMovement {

    func forward(speedPercent: Int) {
        print(speedPercent)
    }

    func reverse(speedPercent: Int) {
        print(speedPercent)
    }

    func left(speedPercent: Int) {
        print(speedPercent)
    }

    func right(speedPercent: Int) {
        print(speedPercent)
    }

}

现在作为 EnemyInstance 初始化程序的参数传递 Movements

的新实例
var enemy = EnemyInstance(name: "zombie", enemyMovement: Movements())

然后你可以在你的 class 的 enemyMovement 属性 上调用一些方法并执行这个特定方法中的代码(在这种情况下它应该打印 speedPercent

required init (name: String, enemyMovement: EnemyMovement) {
    self.name = name
    self.enemyMovement = enemyMovement
    enemyMovement.forward(speedPercent: 2) // prints 2
}