简体   繁体   中英

How to obtain a String from a dictionary and make sure it is not null? (Swift / iOS)

How do I obtain the value from a dictionary, which could also be null, from a key in Swift? The return value cannot be null (if there is no such value in the dictionary, it should fill it as '""')

Example code:

func getValue(data:[String:AnyObject], key:String!) -> String! {
    guard let value:String! = data[key] else {
        return ""
    }
    return value
}

The code above does not build.

Much easier:

return data [key] as? String ?? "";

(Thanks, Thilo) However, why are you calling a method "getValue" when you know that it returns a string? Your method name should express what the method does. Your method returns a string from the dictionary or an empty string. What about calling it getStringOrEmpty?

You should also consider the situation that the in a dictionary coming from JSON, the value could be null, it could be a number, it could even be an array. You should determine what you want to do in these situations. I would at least add some debugging code if the value is not a string.

How about

func getValue(data:[String:Any], key:String) -> String {
    guard let value = data[key] as? String else {
        return ""
    }
    return value
}

This will return the empty String if the key is not present or not a String.

Note that I changed from AnyObject to Any because Strings are not objects.

If you want, you can make both data and key optional, too:

func getValue(data:[String:Any]?, key:String?) -> String {
    guard let k = key, let value = data?[k] as? String else {
        return ""
    }
    return value
}

Try this out

func getValue(data:[String:AnyObject], key:String!) -> String! {
    guard let value:String! = data[key] as! String else {
        return ""
    }
    return value
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM