Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift generic array with type constraint

Tags:

generics

swift

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

like image 294
bandejapaisa Avatar asked Aug 15 '26 18:08

bandejapaisa


1 Answers

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.

like image 197
Antonio Avatar answered Aug 17 '26 13:08

Antonio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!