gpt4 book ai didi

swift - 修改枚举关联值

转载 作者:行者123 更新时间:2023-11-30 10:04:40 26 4
gpt4 key购买 nike

有什么方法可以在 Swift 中修改枚举的关联值吗?我这样做,但每次我都必须覆盖整个对象。这并不优雅。

    switch option {
case .Days(let choices):
var newChoices = choices

...

self.days = Option.Days(newChoices)

default:
break
}

最佳答案

不允许修改枚举大小写的关联值,但您可以使用具有引用语义的类型(即class)在容器内附加可变值,如下所示:

class Box<T>: CustomDebugStringConvertible {
var value: T
var debugDescription: String { return "\(value)" }
init(_ value: T) { self.value = value }
}

enum X {
case A(Box<Int>), B(Box<String>)
}

let x = X.A(Box(1))
let y = X.B(Box("xxx"))

print(x, y) // A(1) B(xxx)

if case let X.A(box) = x {
box.value = 2
}

if case let X.B(box) = y {
box.value = "yyy"
}

print(x, y) // A(2) B(yyy)

不过,我觉得它看起来不太优雅。

关于swift - 修改枚举关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36761757/

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