others-how to solve Type of expression is ambiguous without more context with swift?

1. Purpose

In this post, I would show how to solve this problem:

Type of expression is ambiguous without more context

2. Environment

  • Mac OS 10.15
  • Swift 5
  • Xcode 12

3. The solution

3.1 The code that cause the problem

    func processJson(json:Any) -> Void {
        if let myJsonDict = json as? [String:Any] {
            let requestId = myJsonDict["requestId"]
            if let myMessageListArray = myJsonDict["messageList"] as? [Any] {
                for msg in myMessageListArray {
                    if let msgJsonDict = msg as? [String:Any] {
                        let body = msgJsonDict["body"]
                        let fromAddress = msgJsonDict["fromAddress"]
                        print("msg body \(body), fromAddress \(fromAddress)")
                        self.addNewMessage(theMessageContent: body, theFromAddress: fromAddress) 
                    }
                }
            }
        }
    }

The problem occurred at these lines:

let body = msgJsonDict["body"]
let fromAddress = msgJsonDict["fromAddress"]

3.2 The solution

Here is the code that compiles ok:

   func processJson(json:Any) -> Void {
        if let myJsonDict = json as? [String:Any] {
            let requestId = myJsonDict["requestId"]
            if let myMessageListArray = myJsonDict["messageList"] as? [Any] {
                for msg in myMessageListArray {
                    if let msgJsonDict = msg as? [String:Any] {
                        let body = msgJsonDict["body"] as! String //key point
                        let fromAddress = msgJsonDict["fromAddress"] as! String //key point
                        print("msg body \(body), fromAddress \(fromAddress)")
                        self.addNewMessage(theMessageContent: body, theFromAddress: fromAddress)
                    }
                }
            }
        }
    }

Here is the key point:

let body = msgJsonDict["body"] as! String //key point
let fromAddress = msgJsonDict["fromAddress"] as! String //key point

Now it works!

4. Summary

In this post, I demonstrated how to solve Type of expression is ambiguous without more context problem when using swift to do some dict jobs.

-->