mercredi 12 août 2015

Reflection and typeChecking for optionals

Playing with reflections in swift 2.0 i'm trying to type check a child value.

The problem: each element of the children array in the Mirror of Any item is not optional, but his type can be optional... What happens is that of course i have the child value even if the value is nil

Maybe it is not clear so i put here some code to explain better.

For convenience i defined a subscript in a Mirror extension that fetches the child object with a given label

extension Mirror {
    public subscript(key: String)->Child?{
        var child = children.filter {
            var valid = false
            if let label = $0.label {
                valid = label == key
            }
            return valid
            }.last
        if child == nil,
            let superMirror = superclassMirror() {
                child = superMirror[key]
        }
        return child
    }
}

perfect, now let's say i have this class

class Rule: NSObject, AProtocol {
    var hello: String?
    var subRule: Rule?
}

Ok, now the problem

let aRule = Rule()
let mirroredRule = Mirror(reflecting:aRule)
if let child = mirroredRule["subRule"] {
     //child.value always exists
     //i can't do child.value is AProtocol? because child.value is not optional
     //child.value is AProtocol of course returns false
     //child.dynamicType is Optional(Rule)
}

child.value has not been initialized so it is nil, and i can't check his type using the unwrap function

private func unwrap(subject: Any) -> Any? {
    var value: Any?
    let mirrored = Mirror(reflecting:subject)
    if mirrored.displayStyle != .Optional {
        value = subject
    } else if let firstChild = mirrored.children.first {
        value = firstChild.value
    }
    return value
}

I hope the problem is clear. Any suggestions?





Aucun commentaire:

Enregistrer un commentaire