Search code examples
swiftdictionaryoption-type

getting a Optional value in dictionary


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"


Solution

  • 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"])