gpt4 book ai didi

Swift 在函数返回枚举时给我错误

转载 作者:搜寻专家 更新时间:2023-11-01 05:54:59 26 4
gpt4 key购买 nike

为什么这不起作用?

enum SwitchStatus {
case on
case off
}

var switchStatus: SwitchStatus = .off

func flipSwitch() -> SwitchStatus {
return !switchStatus
}

我在 return !switchStatus 收到这个错误:

Cannot convert value of type 'SwitchStatus' to expected argument type 'Bool'

如果我说返回 SwitchStatus,为什么它期望 Bool

最佳答案

! 是“逻辑非”运算符并采用 Bool 参数,因此编译器已经在 !switchStatus 表达式上提示了。

您可以通过定义

! 扩展到 SwitchStatus 参数
prefix func !(arg: SwitchStatus) -> SwitchStatus

函数,但我实际上要做的是定义一个 flip() 方法,类似于已被 added to Bool in Swift 4.2toggle() 方法:

enum SwitchStatus {
case on
case off

mutating func flip() {
switch self {
case .on: self = .off
case .off: self = .on
}
}
}

然后你可以做

var switchStatus: SwitchStatus = .on

switchStatus.flip() // Switch if off ...
switchStatus.flip() // ... and on again.

关于Swift 在函数返回枚举时给我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51844405/

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