Using a Type Variable in a Generic
Solution 1:
Swift's static typing means the type of a variable must be known at compile time.
In the context of a generic function func foo<T>() { ... }
, T looks like a variable, but its type is actually known at compile time based on where the function is called from. The behavior of Array<T>()
depends on T
, but this information is known at compile time.
When using protocols, Swift employs dynamic dispatch, so you can write Array<MyProtocol>()
, and the array simply stores references to things which implement MyProtocol
— so when you get something out of the array, you have access to all functions/variables/typealiases required by MyProtocol
.
But if t
is actually a variable of kind Any.Type
, Array<t>()
is meaningless since its type is actually not known at compile time. (Since Array
is a generic struct, the compiler needs know which type to use as the generic parameter, but this is not possible.)
I would recommend watching some videos from WWDC this year:
- Protocol-Oriented Programming in Swift
- Building Better Apps with Value Types in Swift
I found this slide particularly helpful for understanding protocols and dynamic dispatch:
Solution 2:
There is a way and it's called generics. You could do something like that.
class func foo() {
test(Int.self)
}
class func test<T>(t: T.Type) {
var arr = Array<T>()
}
You will need to hint the compiler at the type you want to specialize the function with, one way or another. Another way is with return param (discarded in that case):
class func foo() {
let _:Int = test()
}
class func test<T>() -> T {
var arr = Array<T>()
}
And using generics on a class (or struct) you don't need the extra param:
class Whatever<T> {
var array = [T]() // another way to init the array.
}
let we = Whatever<Int>()
Solution 3:
jtbandes' answer - that you can't use your current approach because Swift is statically typed - is correct.
However, if you're willing to create a whitelist of allowable types in your array, for example in an enum
, you can dynamically initialize different types at runtime.
First, create an enum
of allowable types:
enum Types {
case Int
case String
}
Create an Example
class. Implement your someTypes()
function to use these enum values. (You could easily transform a JSON array of strings into an array of this enum.)
class Example {
func someTypes() -> [Types] {
var ret = [Types]()
for _ in 1...rand()%10 {
if (rand()%2 == 0){ ret.append(.Int) }
else {ret.append(.String) }
}
return ret
}
Now implement your test function, using switch
to scope arr
for each allowable type:
func test() {
let types = self.someTypes()
for type in types {
switch type {
case .Int:
var arr = [Int]()
arr += [4]
case .String:
var arr = [String]()
arr += ["hi"]
}
}
}
}
As you may know, you could alternatively declare arr
as [Any]
to mix types (the "heterogenous" case in jtbandes' answer):
var arr = [Any]()
for type in types {
switch type {
case .Int:
arr += [4]
case .String:
arr += ["hi"]
}
}
print(arr)