Properties with generic type

梦想的初衷 提交于 2020-02-23 07:04:13

问题


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
      ...
    }
  }
}

回答1:


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"



回答2:


In general the answer is no.

In your example, genericProperty would have a different type in the subclass to the superclass and that would break the type system. If you could do it, you could then legitmiately try something like this:

var array: [Value] = []
array.append(IntValue())
array.append(FloatValue())

for v in array
{
    let foo = v.genericProperty
}

What should the compiler infer for the type of foo?



来源:https://stackoverflow.com/questions/48830357/properties-with-generic-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!