[swift-users] Bool with Foundation framework, can convert to AnyObject

zh ao owenzx at gmail.com
Wed May 25 04:11:13 CDT 2016


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160525/f8927531/attachment.html>


More information about the swift-users mailing list