swiftwatchkitxcode7-beta6

Immutable value in Swift 2


I have a project in which this code does not give me problems, but in Xcode 7.0 beta 6 it skips the warning and I can't find a way to fix it

 func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
    print("Mensaje recibido:\(message)")

    if let msg = message as? String{ //Error here
        // do something with the uname
    }

    replyHandler(["reply" : "OK"])
}

Solution

  • As Mr Beardsley said, the instruction if let msg = message as? String won't work because you're trying to cast message, which is a dictionary, to a String optional. This should do the job:

    func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
    print("Mensaje recibido:\(message)")
    
    if let msg = message["/* Whatever key you want to select */"] as? String {
        // do something with the uname
    }
    
    replyHandler(["reply" : "OK"])
    

    }

    Replace the 'Whatever key you want to select' part with the key paired to the value you want to assign to msg.