我正在玩Swift枚举,并想知道是否有办法改变枚举的值,例如下面的代码尝试但失败。
enum myEnum {
case SomeCase(Int?)
mutating func someFunc() {
switch self {
case .SomeCase(let a):
if a != nil {
// a = 5 can't do this of course as assigning to let
var temp = a!; // but this generates a warning
temp = 5;
}
}
}
}
如果目前还没有,那么当变异枚举进入XCode时会不会这样?
答案 0 :(得分:1)
整个枚举是单个值,因此您必须完全替换它,而不是逐个字段。但你可以通过替换self
。
enum MyEnum {
case SomeCase(Int?)
mutating func someFunc() {
switch self {
case .SomeCase(_):
self = .SomeCase(5)
}
}
}
// You have to use `var` here of course or you can't mutate it.
var x = MyEnum.SomeCase(1) // .SomeCase(Optional(1))
x.someFunc() // .SomeCase(Optional(5))
答案 1 :(得分:0)
Rob Napier的答案很好,但我对你的问题有不同的理解。我会写这样的东西:
enum MyEnum {
case SomeCase(Int?)
mutating func someFunc() {
switch self {
case .SomeCase(.Some(_)):
self = .SomeCase(5)
default:
// or case .SomeCase(.None): if you prefer
break
}
}
}
使用此代码时,enum
会随someFunc
变异,当且仅当其关联值不是nil
时。因此,我在Playground中测试时得到以下结果(结果显示为注释):
var x = MyEnum.SomeCase(nil)
switch x {
case .SomeCase(.Some(let a)):
println(a)
default:
println("Associated value is nil") // Will print "Associated value is nil"
}
x = MyEnum.SomeCase(20)
x.someFunc()
switch x {
case .SomeCase(.Some(let a)):
println(a) // Will print 5
default:
println("Associated value is nil")
}