3

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This [T: AProtocol]() is not array, but dictionary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.