gpt4 book ai didi

ios - 协议(protocol)方法/函数中的 Swift 默认参数和忽略参数

转载 作者:搜寻专家 更新时间:2023-10-31 08:08:50 24 4
gpt4 key购买 nike

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

我有这个协议(protocol):

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

有了这两个特殊类:

//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
}
}

最佳答案

首先,在协议(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即使它是方法的第一个参数。您可以使用 _ 作为显式 external name 覆盖该行为:

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

在您的OfflineGame 情况下,您可以忽略以_ 作为内部名称 的参数:

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

关于ios - 协议(protocol)方法/函数中的 Swift 默认参数和忽略参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27922432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com