I am working on a set of classes representing entities and their properties, which can then dynamically create an editor table view from an object. These properties use generics to capture the type of property. To use KVO and generate an automatic setter, these properties contain a key path. Here is a very simplified version of the property class:
class XUEntityProperty<Entity: NSManagedObject, Value> {
let keyPath: String
var customSetter: ((Entity, Value) -> Void)?
func setValue(value: Value, onEntity entity: Entity) {
if let setter = self.customSetter {
setter(entity, value)
return
}
guard let objValue = value as? AnyObject else {
XUThrowAbstractException()
}
entity.setValue(objValue, forKeyPath: self.keyPath)
}
}
It works very well with almost anything. The problem is when it comes to options. For example:.
let property = XUEntityProperty<MyEntity, NSDate?>(keyPath: "optionalDate")
The problem here is that in the method, setValuecasting to AnyObjectfails, because a value Optional<NSDate>that cannot be attributed to AnyObject- objValue as? NSDatewill return nil, even if it objValueis .Some(_).
, , Optional.
, , , , , Optional Optional.
- , , Any Optional, , , AnyObject?
, :
let any: Any = Optional<String>("123")
any.dynamicType
var object: AnyObject? = nil