是否可以具有泛型类型的属性?
我正在尝试做的事情:
Value
使用以下结构调用基类:
class Value {
var genericProperty: T
init<T>(type: T) {
switch type.self {
case is Int.Type:
genericProperty is Int
case is [Int.Type]:
genericProperty is [Int]
default:
genericProperty is Any
}
}
}
然后有一堆定义genericProperty
应该是什么类型的子类。
像这样的东西:
class IntValue: Value {
override init<T>(type: T) {
super.init(type: Int.self)
}
}
class IntArrayValue: Value {
override init<T>(type: T) {
super.init(type: [Int.self])
}
}
这是否以某种方式可能associatedType
?
为了澄清(可能这种设计很糟糕)。我想沿着这条线做一些事情:
func handle(values: [Value]) {
values.forEach {
switch $0 {
case is IntValue.Type:
// Here I will now know that `genericProperty` will have type `Int`
// and can assign to a property with `Int` type
property: Int = $0.genericProperty
case is IntArrayValue.Type:
// Here I know it will be an array
...
}
}
}
不确定这是否是您要查找的内容,但是...您可以创建一个通用基类并添加指定具体类型的子类:
class Value<T> {
var value: T
init(_ value: T) {
self.value = value
}
}
现在一些具有特定值类型的子类:
class IntValue: Value<Int> {}
class StringValue: Value<String> {}
以下是它们的使用方法:
let intValue = IntValue(42)
intValue.value // 42
let stringValue = StringValue("Hi")
stringValue.value // "Hi"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句