Dictionary<String, AnyObject> can accept Bool as a Value, but my own function can't


(Zhao Xin) #1

See the code:

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"

    update(aBool, key: key)

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

    dictionary.updateValue(aBool, forKey: key)

    // works

}

My own function will get the error as shown in the comment part. But it
seams that Dictionary<String, AnyObject> has no issue. How to improving my
code?

Zhaoxin


(Jeremy Pereira) #2

Bool is a struct in Swift and doesn’t inherit from AnyObject.

The reason why dictionary.updateValue(aBool, forKey: key) works for you is that you have imported Foundation. which enables bridging between Dictionary and Foundation.NSDictionary, including converting value arguments into an Objective-C type.

···

On 25 May 2016, at 05:07, zh ao via swift-users <swift-users@swift.org> wrote:

See the code:

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"
    
    update(aBool, key: key)
    // cannot invoke 'update' with an argument list of type '(Bool, key: String)'
    
    dictionary.updateValue(aBool, forKey: key)
    // works
}

My own function will get the error as shown in the comment part. But it seams that Dictionary<String, AnyObject> has no issue. How to improving my code?

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