协议方法/函数中的Swift默认参数和ignore参数

时间:2015-01-13 12:40:48

标签: ios swift arguments protocols

如何设置协议的功能,以便它可以接收可选参数甚至忽略它?

我有这个协议:

protocol Game {
    func modeName(forRound: Int) -> ModeName
}

使用这2个特殊类:

//Goal: Default forRound should be 0 if none provided
class OnlineGame : Game {
    func modeName(forRound: Int = 0) -> ModeName {
        //Some code
    }
}

//Goal: I don't care about the forRound value here
class OfflineGame : Game {
    func modeName(_ forRound: Int) -> ModeName {
        //Some code
    }
}

1 个答案:

答案 0 :(得分:0)

首先,在protocol中,您宣布“方法”和the first parameter of "method" has no external name by default。所以这是正常案例代码:

class SomeGame: Game {
    func modeName(forRound: Int) -> ModeName {
        // ...
    }
}

let game: Game = SomeGame()
let modeName = game.modeName(1) // not `game.modeName(forRound: 1)`

OnlineGame案例if the parameter has default value, it has external name automatically中,即使它是该方法的第一个参数。您可以使用_覆盖该行为作为显式外部名称

class OnlineGame : Game {
    func modeName(_ forRound: Int = 0) -> ModeName {
        //Some code
    }
}

OfflineGame案例中,您可以将参数_忽略为内部名称

class OfflineGame : Game {
    func modeName(_: Int) -> ModeName {
        //Some code
    }
}