根据swift.org上的文档,以下是原始源代码:
https://docs.swift.org/swift-book/LanguageGuide/Protocols.html
class DiceGameTracker: DiceGameDelegate {
var numberOfTurns = 0
func gameDidStart(_ game: DiceGame) {
numberOfTurns = 0
if game is SnakesAndLadders {
print("Started a new game of Snakes and Ladders")
}
print("The game is using a \(game.dice.sides)-sided dice")
}
func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) {
numberOfTurns += 1
print("Rolled a \(diceRoll)")
}
func gameDidEnd(_ game: DiceGame) {
print("The game lasted for \(numberOfTurns) turns")
}
}
我知道func gameDidStart使用DiceGame类型的游戏参数来访问.dice.sides并检查引用对象。
但是
func gameDidEnd(_ game: DiceGame)
和func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
这两个函数不使用game参数,为什么还要声明它呢?它是Apple的编码样式吗?我真的不明白这部分... 最佳答案
简单的答案是肯定的,这是苹果公司的故意选择。该参数是协议方法声明的必需部分:
protocol DiceGameDelegate: AnyObject {
func gameDidStart(_ game: DiceGame)
func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
func gameDidEnd(_ game: DiceGame)
}
因此,为了符合协议,无论是否使用它,它都必须包含参数。