Swift – Workarounds for generic variable in Swift

genericsswifttuplestype-aliasvariables

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

Best Solution

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