Home > other >  How do I access a value on an [String: Any] Dictionary in Swift
How do I access a value on an [String: Any] Dictionary in Swift

Time:11-03

Currently, I have a dictionary with values on it, some of them are Objects, the values in the dictionary are as follows

["otherUserId": id,
"otherUser": {
    email = "[email protected]";
    name = zakmint;
    profileImageURL = "url";
 },
"lastMessage": {
    fromId = id;
    hasReadMessage = 0;
    text = What;
    timestamp = 1635800286;
    toId = id;
    type = TEXT;
},
"timeStamp": 1635800286]

How do I access the value of hasReadMessage, I am currently grabbing the dictionary like this then trying to access the value on top of it. But it has the type Any and Im not sure how to access the value without causing a compilation error.

                if let childSnapshot = child as? DataSnapshot {
                    guard let dictionary = childSnapshot.value as? [String: Any] else { return }
                    print(dictionary)
                    let lastMessage = dictionary["lastMessage"]
                
                    let value = lastMessage.hasReadMessage

CodePudding user response:

You cannot treat a dictionary as a struct. The keys are not properties whose value can be accessed by dot notation.

You have to use key subscription and conditionally downcast each intermediate value to its proper type

guard let childSnapshot = child as? DataSnapshot, 
      let dictionary = childSnapshot.value as? [String:Any],
      let lastMessage = dictionary["lastMessage"] as? [String:Any],
      let hasReadMessage = lastMessage["hasReadMessage"] as? Bool else { return }

print(hasReadMessage)
               
  • Related