gpt4 book ai didi

Swift enum - 约束关联值

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:23 26 4
gpt4 key购买 nike

我有一个代表线宽的枚举,它可以是恒定宽度,也可以是相对于它所在 View 大小的宽度。

enum Thickness {
case Constant(Float) // where value ≥ 0
case Relative(Float) // where 0 ≤ value ≤ 1
}

有没有办法将这些关联的值约束构建到枚举类型中?我目前正在对这种类型的属性使用 didSet 属性观察器:

var lineThickness: Thickness {
didSet {
switch lineThickness {
case let .Relative(x): lineThickness = .Relative(min(max(x, 0), 1))
case let .Constant(x): lineThickness = .Constant(max(x, 0))
}
}
}

但如果我能为整个类型做一次,而不是为每个属性复制这个观察者,那就更整洁了。

我知道我可以为枚举创建初始化程序或方法,但我不确定是否/如何使用它来约束关联值?

最佳答案

好吧,这不是最好的优雅,但至少它会让你避免因为忘记到处都是观察者而导致的错误......

struct Thickness {
enum Type {
case Constant
case Relative
}
let type: Type
let value: Float

init(type: Type, value: Float) {
self.type = type;
switch type {
case .Constant:
self.value = max(value, 0)
case .Relative:
self.value = min(max(value, 0), 1)
}
}
}

关于Swift enum - 约束关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27898601/

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