2

I can't understand why I can't pass an array of structs (which implement a protocol) to a function expecting an array of things that conform to that protocol.

I get a compile error at: r.setDataToRender(toRender) --> Cannot convert value of type [Process] to expected argument type [MyType].

What I can do is to create an array [MyType] and append each element of toRender and pass that new array instead, but that seems inefficient.

//: Playground - noun: a place where people can play
typealias MyType = protocol<Nameable, Countable>

protocol Nameable {
    func getName() -> String
}

protocol Countable {
    func getCount() -> Int
}

struct Process : MyType {
    let processName: String?
    let count: Int?

    init(name:String, number: Int) {processName = name; count = number}
    func getCount() -> Int {return count!}
    func getName() -> String {return processName!}
}

class Renderer {
    var data  = [MyType]()

    func setDataToRender(d: [MyType]) {
        data = d
    }

    func setOneProcessToRender(d: Process) {
        var temp = [MyType]()
        temp.append(d)
        data = temp
    }
}

var toRender = [Process]()
toRender.append(Process(name: "pro1",number: 3))

let r = Renderer()
r.setOneProcessToRender(Process(name: "pro2",number: 5)) // OK
r.setDataToRender(toRender) // KO

var str = "Hello, Stackoverflow!"

1 Answer 1

1

It works if you change it to this:

var toRender = [MyType]()
toRender.append(Process(name: "pro1",number: 3))

Your function setDataToRender is expecting an array of types MyType. When you instantiated your array you typed it to Process. Although Process implements MyType it is not identical to MyType. So you have to create toRender as an array of types MyType to be able to send it to setDataToRender.

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

1 Comment

Hi :). Yes, I know, that's the equivalent of what I did in setOneProcessToRender(). Doing r.setDataToRender(toRender.map{$0}) also works and I also don't understand why because if I put the result of toRender.map{$0} in a var, Xcode will tell me that the type of that var is [Process]. So still trying to understand why Process "satisfies" MyType but an array of Process doesn't satisfy a function expecting an array of MyType. If I change setOneProcessToRender to expect a MyType, it's fine to send a Process. So what works for a single element doesn't work for an array of these same elements.

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.