swift - Assigning an array of structs to an array of protocols -


let's have following:

protocol myprotocol { }  struct mystruct: myprotocol { }  var s1 = mystruct() var s2 = mystruct() var s3 = mystruct()  var structarray = [s1, s2, s3] 

when try assign array of structs array of protocols (that each struct in structarray conforms to):

var protocolarray:[myprotocol] = structarray 

i error: cannot convert array of type '[mystruct]' specified type '[myprotocol]'

i expect since each object in array conforms protocol ok "an array of structs conform protocol" assignable expects "an array of conforms protocol". maybe doesn't apply when type "an array of " vs "thing", if makes sense.

for example, valid:

var p1:myprotocol = s1 

because s1 conforms myprotocol. if use arrays doesn't seem hold anymore.

incidentally, seems work too:

var p1array:[myprotocol] = [s1, s2, s3] 

presumably because type of array determined [myprotocol] , isn't predetermined previous variable (like in example above).

so anyways, ask: what's best way around this? how can assign array of structs (that conform protocol) array type "an array of things conform protocol".

i'm new swift may missing trivial.

i map array type need:

var protocolarray: [myprotocol] = structarray.map { $0 myprotocol } 

when that, can rid of type annotation, expression whole isn't longer:

var protocolarray = structarray.map { $0 myprotocol } 

swift won't automatically convert between array types, if compatible. have explicit 1 way or another.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -