所以我有一个类型别名元组
public typealias MyTuple<T> = (key: T, value: String)
在我的 ViewController 中,我想声明一个具有通用数据类型的 MyTuple 数组,因为我还不知道键的类型。然而,来自this在 Swift 中不可能有泛型变量。还有其他解决方法如下,但我都不喜欢它们中的任何一个。谁有更好的想法?
class ViewController: UIViewController {
var array1 = [MyTuple<T>]() // compile error of course
var array2 = [MyTuple<Any>]() // no point as I'd use `Any` for MyTuple
func getArray<T>(array: Array<MyTuple<T>>) -> Array<MyTuple<T>> {
return array // not a good approach
}
}
最佳答案
我认为解决这个问题的通常方法是将类型决策“推”到依赖链的上游,到 View Controller :
class ViewController<T>: UIViewController {
var array: [MyTuple<T>]
}
这是有道理的,因为您可能会将 Controller 视为“foo Controller ”,其中“foo”是 T
的具体值。 (“宠物 Controller ”、“产品 Controller ”等)但是,在知 Prop 体类型之前,您当然无法创建数组的实例。
关于swift - Swift 中泛型变量的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44469650/