Workarounds for generic variable in Swift

偶尔善良 提交于 2019-12-05 02:24:41

问题


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

回答1:


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




回答2:


I think the usual way to solve this is to “push” the type decision higher up the dependency chain, to the view controller:

class ViewController<T>: UIViewController {
    var array: [MyTuple<T>]
}

That makes sense, since you would probably think about the controller as a “foo controller”, where “foo” is the concrete value of T. (A “pet controller”, a “product controller,” etc.) But of course you can’t create an instance of the array until you know the concrete type.



来源:https://stackoverflow.com/questions/44469650/workarounds-for-generic-variable-in-swift

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