Swift中泛型变量的解决方法 [英] Workarounds for generic variable in Swift
问题描述
public typealias MyTuple< T> =(key:T,value:String)
在我的ViewController中,我想声明一个数组MyTuple与泛型数据类型,我仍然不知道键的类型。但是,从这,不可能在Swift中有一个泛型类型的变量。还有其他的解决方法如下,但我不喜欢他们中的任何一个。任何人都有更好的想法?
类ViewController:UIViewController {
var array1 = [MyTuple< T>]()/ /编译错误当然
var array2 = [MyTuple< Any>]()//没有意义,因为我会使用MyTuple的`Any`
func getArray< T> ;(array:Array< MyTuple< T>) - >阵列< MyTuple< T>> {
return array // not a good approach
}
}
您可以使用不依赖于键的数据类型的数组声明和基本方法的协议来做类似的操作:
protocol KeyValueArray
{
associatedtype KeyType
var array:[(key:KeyType,value:String)] {get set}
扩展KeyValueArray
{
var array:[(key:KeyType,value:String)] {get {return []} set {}}
}
类ViewController:UIViewController,KeyValueArray
{
//假设这就像一个abstact基类
//不会被实例化。
typealias KeyType =任何
//您可以使用数组变量
//实现基类函数,只要它们不依赖于特定的键类型。
class SpecificVC:ViewController
{
typealias KeyType = Int
var array:[(key:Int,value:String)] = [ ]
}
我假设在某些时候视图的具体实例控制器子类将具有键的实际类型
So I have a typealias tuple
public typealias MyTuple<T> = (key: T, value: String)
In my ViewController, I want to declare an array of MyTuple with generic data type as I still don't know the type for key yet. However, from this it is impossible to have a generic-type variable in Swift. There are other workarounds as follows but I don't like either of them. Anyone has better ideas?
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
}
}
You could do something similar using a protocol for the array declaration and base methods that are not dependent on the data type of the key:
protocol KeyValueArray
{
associatedtype KeyType
var array:[(key:KeyType,value:String)] { get set }
}
extension KeyValueArray
{
var array:[(key: KeyType, value:String)] { get {return []} set { } }
}
class ViewController:UIViewController,KeyValueArray
{
// assuming this is like an "abstact" base class
// that won't actually be instantiated.
typealias KeyType = Any
// you can implement base class functions using the array variable
// as long as they're not dependent on a specific key type.
}
class SpecificVC:ViewController
{
typealias KeyType = Int
var array:[(key:Int,value:String)] = []
}
I'm assuming that, at some point the concrete instances of the view controller subclasses will have an actual type for the keys
这篇关于Swift中泛型变量的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!