skip to Main Content

I have the following JSON:
{

payload =     {
    asks =         (
                    {
            price = "6.38";
            quantity = 100;
        }
    );
    bids =         (
                    {
            price = "6.37";
            quantity = 118;
        }
    );
    depth = 1;
};

And I have the following code:

      let payload = parsedJSON.object(forKey: "payload") as AnyObject
      let bids = payload.object(forKey: "bids") as AnyObject
      if bids.count > 0 {
            let bprice = (bids[0] as AnyObject).object(forKey: "price") as! Double
            let asks = payload.object(forKey: "asks") as AnyObject
            let aprice = (asks[0] as AnyObject).object(forKey: "price") as! Double
      }

Xcode is 12.5. Swift is 5.
For IOS everything is working.
As soon as I try to build app for My Mac I got the following error:
Ambiguous use of ‘object(forKey:)’

enter image description here

What is wrong? Why for IOS it is working but for Mac it doesn’t work?
How to fix this?
I read a lot of advices with "to change type to [String:Any]" but it doesn’t work.

2

Answers


  1. Chosen as BEST ANSWER

    Somebody gave me good and advice and cleared it:

    if let payload = parsedJSON["payload"] as? [String: Any],
    let bids = payload["bids"] as? [[String: Any]],
    let asks = payload["asks"] as? [[String: Any]],
    let bid = bids.first,
    let ask = asks.first {
        let bprice = bid["price"] as? Double ?? 0
        let aprice = ask["price"] as? Double ?? 0
    }
    

    And looks like it is working. But I am quite confused how to work with arrays here. I can use asks.first like asks[0] and asks.last like asks[asks.count-1] but for asks[1] Xcode gives error. How to code this correctly? enter image description here


  2. Try this – assuming parsedJSON is [String: Any]

    if let payload = parsedJSON["payload"] as? [String: Any],
       let bids = payload["bids"] as? [[String: Any]],
       let asks = payload["asks"] as? [[String: Any]],
       let bid = bids.first,
       let ask = asks.first {
          let bprice = bid["price"] as? Double ?? 0
          let aprice = ask["price"] as? Double ?? 0
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search