ios - Swift4.2 : Why func gameDidEnd(_:) no need to use game parameter but still declare in the function?

标签 ios swift delegates protocols

根据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) 这两个函数没有使用游戏参数,为什么还要声明呢?它是Apple的编码风格吗?我真的不明白这部分....

最佳答案

简单的回答是肯定的,这是 Apple 深思熟虑的选择。该参数是协议(protocol)方法声明的必需部分:

protocol DiceGameDelegate: AnyObject {
    func gameDidStart(_ game: DiceGame)
    func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
    func gameDidEnd(_ game: DiceGame)
}

因此,为了符合协议(protocol),无论您是否使用它,它都必须包含该参数。

关于ios - Swift4.2 : Why func gameDidEnd(_:) no need to use game parameter but still declare in the function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52009021/

相关文章:

ios - googlemap sdk 与 ios 架构有问题

ios - 无法将类型 '[String]' 的值分配给类型“String”? swift 2

swift - ios 11 自定义导航栏位于状态栏下方

ios - 在 iOS Action Extension 中使用 SwiftUI 内容 View 而不是 Action ViewController 启动

ios - 尽管已初始化,但仍委托(delegate) : MKMapView is nil,

iphone - 获取网页图片

ios - 网络状态0 = 类型错误: 'undefined' is not a function

ios - 在 Swift 中的不同 View Controller 上显示特定用户及其存储在解析中的所有信息

swift - 使用 Swift 委托(delegate)

c# - 委托(delegate)参数中的 Co(ntra) 方差