Swift: casting Any to array of protocol objects -


there protocol:

protocol valuable {     func value() -> int } 

and class implements protocol:

class value: valuable {     private let v: int      init(value: int) {         v = value     }      func value() -> int {         return v     } } 

there array of value objects stored in variable of type:

let any: = [value(value: 1), value(value: 2), value(value: 3)] 

it possible cast [value]:

let arrayofvalue = as? [value] // [1, 2, 3] 

why not possible case [valuable]?

let arrayofvaluable = as! [valuable] // compiler error bad instruction let arrayofvaluable2 = as? [valuable] // nil 

updated: in swift3 entirely possible cast [any] [valuable]. cast succeed long elements in array can casted; cast fail otherwise.

var strings: [any] = ["cadena"] var mixed: [any] = ["cadena", 12]  strings as! [string] // ["cadena"] mixed as? [string] // nil mixed as! [string] // error! not cast value... 

previously of swift 2: make [valuable] out of [any] must done manually functions map other answers have explained.

there no covariance nor contravariance generics in swift (as of swift 2). means arrays of different types, [string] or [uiview], cannot casted each other, nor types compared.

[uiview] , [uibutton] bear no hierarchy between each other regardless uibutton subclass of uiview. why if following returns true:

valuable.self any.type // true 

the following casts yield errors same reason:

var anyarray: [any] = ["cadena"]  anyarray as! [string] // bad_instruction error "some string" as! double // bad_instruction error 

the 2 clases bear no relation , cast impossible, since as! forced cast booms error.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -