What's the difference between casting (as) and map on Array?

(Roy Hsu) #1

I know there are multiple ways to convert an array of A to an array of P if A conforms to P protocol.

protocol P { }

struct A: P { }

let array1: [A] = [ A(), A(), A() ]

I am wondering whether the following array transforms are equivalent.
If they were different, how performant between each other?

let array2: [P] = array1

let array3 = array1 as [P]

let array4 = array1.map { $0 as P }

Roy

(Ben Cohen) #2

They are equivalent. The compiler essentially does the map for you when you use as. There may be slight arbitrary performance discrepancies based on what the optimizer does, but hopefully not material ones.

Personally, I wish it didn’t support this kind of as, since it’s O(n), unlike languages where everything is a reference where these casts can be done in constant time. But developers used to those languages would find it very surprising if it isn’t supported.

8 Likes
(Roy Hsu) #3

Thanks. I think I will choose to write the map version due to the cast seems a little magic to me. =)