如何设置协议的功能,以便它可以接收可选参数甚至忽略它?
我有这个协议:
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
}
}
答案 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
}
}