I'm trying to write a swift method that returns a generic array. I've left out some of the details, but kept the important bit that isn't working for clarity...
protocol AProtocol {
func doSomething()
}
func decode<T: AProtocol>(jsonArray: Array<AnyObject>?) -> [T: AProtocol] {
//...
var resultArray = [T: AProtocol]()
resultArray.append
//...
}
When I specify that the array contains type T: AProtocol, then the append method no longer appears
[T: AProtocol] does not have a member named append
In this line of code:
var resultArray = [T: AProtocol]()
you are creating a dictionary having key of T type and value of AProtocol type.
To create an array of AProtocol, just use:
var resultArray = [AProtocol]()
otherwise if you want an array of T:
var resultArray = [T]()
Note that the constraint of T implementing the AProtocol protocol is set in the function declaration, so you don't have to repeat it again when using T in the function body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With