Unexpected Behavior with Swift's Compiler -- Probably

52 views Asked by At

I was doing a WatchKit app, and I faced a very strange behavior which I think probably hasn't to do with WatchKit, but some weird way the compiler is behaving, although not sure if the compiler is the culprit but that's what I suspect.

The scenario is basically this: The user taps a button on the watch app, the watch app sends a message using WCSession.default.sendMessage as follows:

    WCSession.default.sendMessage([
        "request": "AmsterdamData",
    ]) { [weak self] (resultDictionary) in
        guard let self = self else {
            return
        }
        // Some implementation
        print("Message Received")
        
    } errorHandler: { (error) in
        print("SessionActivationState", "Error Occurred", error)         
    }

Then the iOS app gets the message on session:didReceiveMessage: (which I have confirmed is getting called everytime) and sends a message back:

func session(_ session: WCSession, didReceiveMessage message: [String: Any], replyHandler: @escaping ([String: Any]) -> Void) {
    print("didReceiveRequestMessage on iPhone: \(message)")
    guard let request = message["request"] as? String else {
        return
    }
    switch request {
        
    case "AmsterdamData":
        var dataToSend: String? = "hello"
                
        replyHandler([
            "AmsterdamData": dataToSend
        ])
        
    default:
        return
    }
}

Ok, this works and I get the message back in the sendMessage function's result closure. Good. But the compiler complains and gives me a slight warning of

enter image description here

Ok, thank you for reminding me. I could easily do that by a as Any (which is what XCode recommends me) and makes sense because the warning sounds like this = the expression was "implicitly" coerced from String? to Any, and we're just making it explicit. Ok, now passing the value like this, so that we can get protected by XCode's yellow shiny sword (metaphor for the big warnings)

        replyHandler([
            "AmsterdamData": dataToSend as Any
        ])

Even given the messages that Xcode gives, I don't expect this to cause a (big) difference in the logic that actually runs, it would just kinda silence the warning by explicity doing what is already explicit enter image description here

Turns out, if I do the as Any part, the result closure on the watch app in the sendMessage function will not get called, and so doesn't its error closure. Just nothing happens, waiting for its angel of death to kill the process (or not if you have a retain cycle). But, this made me think, is there something I have misunderstood heavily? Is the Xcode message not accurate when it says it's implicitly doing it so let's do it explicitly?

I tried this like 20 times, to make sure it wasn't a connection error or sth. It actually was just because of the as Any part, which is very weird.

0

There are 0 answers