小编Cha*_*roe的帖子

将Any转换为Optional

我正在处理一组表示实体及其属性的类,然后可以动态地从实体创建编辑器表视图.这些属性使用泛型来捕获属性类型.为了使用KVO并生成自动设置器,这些属性包含键路径.这是属性类的一个非常简化的版本:

class XUEntityProperty<Entity: NSManagedObject, Value> {
    let keyPath: String
    var customSetter: ((Entity, Value) -> Void)?

    func setValue(value: Value, onEntity entity: Entity) {
        /// If custom setter is set, use it.
        if let setter = self.customSetter {
            setter(entity, value)
            return
        }

        /// Otherwise set the object using the keypath.
        guard let objValue = value as? AnyObject else {
            XUThrowAbstractException() // Use custom setter
        }

        entity.setValue(objValue, forKeyPath: self.keyPath)
    }
}
Run Code Online (Sandbox Code Playgroud)

几乎任何东西都适用.问题在于选择权问题.例如:

let property = XUEntityProperty<MyEntity, NSDate?>(keyPath: "optionalDate")

这里的问题是,在setValue方法中,强制转换AnyObject将失败,因为值为 …

generics casting swift

4
推荐指数
1
解决办法
995
查看次数

标签 统计

casting ×1

generics ×1

swift ×1