Optional chaining and Array in swift -
let's take these 2 simple classes show problem:
class object{ var name:string? // keep simple... , useless } class testclass { var objects:anyobject[]? func initializeobjects (){ objects?.insert(object(), atindex:0) // error objects?.insert(object(), atindex:1) // error objects?.insert(object(), atindex:2) // error } }
with implementation 3 errors could not find member 'insert'
try add object objects
array.
now, if remove optional objects
definition , optional chain in initializeobjects
works no problem (here working code)
class object{ var name:string? } class testclass { var objects:anyobject[] = anyobject[]() // remove optional , initialize empty array func initializeobjects (){ objects.insert(object(), atindex:0) // remove opt chaining objects.insert(object(), atindex:1) // remove opt chaining objects.insert(object(), atindex:2) // remove opt chaining } }
i can't understand wrong in first implementation. thought checks objects?
if objects
not nil
, @ point adds element using insert:atindex:
. i'm wrong -.-
arrays in swift structs , structs value types.
optionals in swift enums (optional<t>
or implicitlyunwrappedoptional<t>
).
when unwrapping optional (implicitly or explicitly) of value type, constant copy of struct. , can't call mutating
methods on constant struct.
executing objects?.insert(object(), atindex:0)
means this:
if let tmp = objects { tmp.insert(object(), atindex:0) }
as workaround, need assign unwrapped value variable , assign variable optional property. that's how value types work.
this reproducible struct, not arrays:
struct s { var value: int = 0 } var vars: s = s() vars.value = 10 //can called let consts: s = s() consts.value = 10 //cannot called - constant! var optionals: s? = s() optionals?.value = 10 //cannot called, unwrapping makes constant copy! //workaround if optionals { var tmps = optionals! tmps.value = 10 optionals = tmps }
some relevant discussion here: https://devforums.apple.com/thread/233111?tstart=60
Comments
Post a Comment