We were told that Bool can't downcast to AnyObject in Swift. However, with
Foundation framework, we can.

do {

    let a:Bool = true

    let object:AnyObject = a as AnyObject

    object.dynamicType

    // __NSCFBoolean.Type

    let b:Bool = object as! Bool

    b // true

}


This feature works in some code automatically (like in a Dictionary), but
in some other codes(like in a function), you have to downcast it yourself.


do {

    var dictionary = Dictionary<String, AnyObject>()



    func update<T:AnyObject>(value:T, key:String) {

        dictionary.updateValue(value, forKey: key)

    }



    let aBool = true

    let key = "testBool"



    dictionary.updateValue(aBool, forKey: key)

    // works



    update(aBool, key: key)

    // doesn't work. cannot invoke 'update' with an argument list of type
'(Bool, key: String)'



    update(aBool as AnyObject, key:key)

    // works

}


My question: Is this normal? Should it all be automatic or not?


Zhaoxin
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to