3

Let's say I have the following:

protocol MyProtocol {
}

struct MyStruct: MyProtocol {
}

var s1 = MyStruct()
var s2 = MyStruct()
var s3 = MyStruct()

var structArray = [s1, s2, s3]

When I try to assign this array of structs to an array of protocols (that each struct in structArray conforms to):

var protocolArray:[MyProtocol] = structArray

I get this error: Cannot convert array of type '[MyStruct]' to specified type '[MyProtocol]'

I would expect that since each object in the array conforms to the protocol it would be ok to say that "an array of structs that conform to some protocol" is assignable to something that expects "an array of anything that conforms to that protocol". But maybe this doesn't apply when the type is "an array of " vs just "thing", if that makes any sense.

For example, this is valid:

var p1:MyProtocol = s1

Because s1 conforms to MyProtocol. But if you use arrays then it doesn't seem to hold anymore.

Incidentally, this seems to work too:

var p1Array:[MyProtocol] = [s1, s2, s3]

Presumably because the type of the array is determined to be [MyProtocol] and isn't predetermined by some previous variable (like in my example above).

So anyways, all this to ask: What's the best way around this? How can I assign an array of structs (that conform to some protocol) to another array whose type is just "an array of things that conform that protocol".

I'm fairly new to Swift so I may be missing something trivial.

2
  • 2
    There is a bug report about this. Might be you filed it? In case you did not, you might be interested in following the bug report: bugs.swift.org/browse/… Commented Apr 8, 2016 at 15:12
  • @BarbaraRodeker I didn't file it, but thanks for sharing the link! Commented Apr 8, 2016 at 18:31

1 Answer 1

4

I usually just map the array to the type I need:

var protocolArray: [MyProtocol] = structArray.map { $0 as MyProtocol }

When you do that, you can actually get rid of the type annotation, so that the expression as a whole isn't actually that much longer:

var protocolArray = structArray.map { $0 as MyProtocol }

Swift won't automatically convert between array types, even if they are compatible. You have to be explicit about it one way or another.

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

1 Comment

is there some deep reason Swift compiler does not allow raw assigning here?

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.