izik461 izik461 - 7 months ago 33
Swift Question

Can't reach objectForKey - [String : AnyObject] as dictionary

I am using watch connectivity to receive a message (dictionary generated in objectiveC).
The called delegate function (swift) doesn't want to interpret the received dictionary properly.

ObjectForKey is not found on my dict. What is the reason?
Thanks

func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
print("\nWC watch:\n Did receive didReceiveMessage: \(message)")
var messageDict = message as Dictionary<String, AnyObject> //here I wanted to cast to Dictionary
let newState = messageDict.objectForKey(WatchManagerMessageMaskStateKey) //but the messageDict does not know objectForKey
}

Answer

[String : AnyObject] and Dictionary<String, AnyObject> are two notations for exactly the same thing.

objectForKey belongs to NSDictionary, for the Swift native type use key subscription.
You might cast the result to something more specific.

func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
    print("\nWC watch:\n Did receive didReceiveMessage: \(message)")
    let newState = message[WatchManagerMessageMaskStateKey]
    ...
}