为什么这不起作用?
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.2 的 toggle()
方法:
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/