我想编写一个函数,仅接受
Int
或Double
并根据它们返回不同的值。实际用例的特点是 SwiftUI struct: View
具有更复杂的 init()
。如果可能的话,我想避免使用不同的输入类型重复它。这怎么办?
理想情况下,我想要一个如下所示的解决方案:
struct MyStruct<T>: View where T is (Int | Double) { // Specifying type here is the problematic part
var value: T
var description: String
init(_ value: T) {
self.value = value
switch value {
case is Int:
description = "Integer"
case is Double:
description = "Double"
}
}
var body: some View {
Text(description)
}
至少有两个选择:
Int
和Double
在扩展中采用的自定义虚拟协议
protocol IntOrDouble {}
extension Int : IntOrDouble {}
extension Double : IntOrDouble {}
struct MyStruct<T>: View where T : IntOrDouble {
var value: T
let description: String
init(_ value: T) {
self.value = value
description = value is Int ? "Integer" : "Double"
}
var body: some View {
Text(description)
}
}
具有关联值的枚举
enum IntOrDouble {
case integer(Int)
case double(Double)
}
struct MyStruct : View {
var value: IntOrDouble
let description: String
init(value: IntOrDouble) {
self.value = value
switch value {
case .integer:
description = "Integer"
case .double:
description = "Double"
}
}
var body: some View {
Text(description)
}
}