具有泛型类型的属性 [英] Properties with generic type
问题描述
是否可以使用泛型类型的属性?
我试图做的是:
使用以下结构创建一个名为 Value
的基类:
class Value {
var genericProperty:T
init< T>(type:T){
switch type.self {
case is Int.Type:
genericProperty是Int
的情况是[Int.Type]:
genericProperty是[Int]
默认值:
genericProperty是任何
}
}
}
然后有一堆子类定义 genericProperty 应该是。
类似这样:
<$ c (类型:T){
super.init(类型:Int.self)
}
} $ b $类的值类型:IntValue:Value {
覆盖init< T> b
class IntArrayValue:Value {
override init< T>(type:T){
super.init(type:[Int.self])
}
$ / code $ / pre
用
associatedType
或任何类型?
澄清(可能这种设计很糟糕)。我想沿着这条线做一些事情:
func句柄(值:[Value]){
值。 forEach {
switch $ 0 {
case is IntValue.Type:
//这里我现在知道'genericProperty`类型为`Int`
//并且可以分配给具有`Int`类型的属性
属性:Int = $ 0.genericProperty
case是IntArrayValue.Type:
//这里我知道它是一个数组
...
解决方案
不知道这是你在找什么,但是...你可以创建一个泛型基类并添加指定具体类型的子类: pre>
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
Is it possible to have properties with generic type?
What I am trying to do:
Have a base class called
Value
with the following structure: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 } } }
Then have a bunch of subclasses that define what the type of
genericProperty
should be.Something like this:
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]) } }
Is this somehow possible with
associatedType
or any of the sorts?For clarification (possibly this design is bad). I would like to do something along this line:
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 ... } } }
解决方案Not sure if that's what you are looking for, but... you can create a generic base class and add subclasses which specify the concrete type:
class Value<T> { var value: T init(_ value: T) { self.value = value } }
Now some subclasses with specific value type:
class IntValue: Value<Int> {} class StringValue: Value<String> {}
And here's how to use them:
let intValue = IntValue(42) intValue.value // 42 let stringValue = StringValue("Hi") stringValue.value // "Hi"
这篇关于具有泛型类型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!