The following code throws a compile error:
import UIKit
class Initable {
required init() {}
}
class NestedObject:Initable {
var nestedProp:String? = nil
}
class MyObj {
var name:String? = nil
var value:Int? = nil
var otherVals:[String]? = nil
var nestedObj:NestedObject? = nil
}
let obj = MyObj()
var nestedObj = obj[keyPath: \MyObj.nestedObj]
if(nestedObj == nil) {
nestedObj = type(of: obj[keyPath: \MyObj.nestedObj]).init()
}
nestedObj![keyPath: \NestedObject.nestedProp] = "NEST ME BABY!!"
obj[keyPath: \MyObj.nestedObj] = nestedObj!
obj
This is due to the fact that type(of: obj[keyPath: \MyObj.nestedObj])
is NestedObject?
, which of course cannot be initialized. I need a way to unwrap the optional typing and get the non-optional typing NestedObject
.
Assumptions that have to be maintained.
- I must used optionals as there is a chance for
nestedObj
to be nil. - I do not know what the type
NestedObject
is. It could be any type, but I am assured those types are allInitable
. - I need to be able to set a property of my
nestedObject
via a keypath. - If
nestedObject
is nil, I need to create a newNestedObject
and set the value via a keypath.
This is a small part of a larger system, so the above assumptions must be considered. I cannot change those.
You can use your optional
Wrapped
type to initialize your nested object:If you want the resulting object to be optional as well:
You need to add those helpers: