Home > Enterprise >  getting a Optional value in dictionary
getting a Optional value in dictionary

Time:07-15

Hi i am a newbie to Swift and i'm now trying to get data using JSON. i have completed getting a JSON data but have no idea how to get the value part using the key. The code below is the part i don't get and trying to solve in a different IDE.

var data = items?[0]["locplc_telno"]
print(data)


var items = Optional([["locplc_telno": Optional("054-602-7799"), ...]])

So the question is:

how can i get "054-602-7799" part using "locplc_telno? I have tried

items?[0]["locplc_telno"]

but got a "nil"

CodePudding user response:

Here are a couple of ways to print values of the dictionary.

var items = Optional([["locplc_telno": Optional("054-602-7799")]])

for item in items! {
    for (key, value) in item {
        print(key, value ?? "")
    }
}
    
print(items?.first?["locplc_telno"])

CodePudding user response:

You can use if let

let text = "[{\"locplc_telno\":\"054-602-7799\"}]"
if let data = text.data(using: .utf8) {
    do {
        let res =  try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]
        if let telno = res?[0]["locplc_telno"] {
            print(telno)
        }
    } catch {
        print(error.localizedDescription)
    }
}

You will get

> 054-602-7799
  • Related