[英]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? 如何从Swift中的键从字典(也可以为null)获取值? The return value cannot be null (if there is no such value in the dictionary, it should fill it as '""') 返回值不能为null(如果字典中没有该值,则应将其填充为““””)
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? (感谢Thilo)但是,当您知道方法返回字符串时,为什么要调用方法“ getValue”? 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? 称它为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. 您还应该考虑以下情况:在来自JSON的字典中,该值可以为null,可以为数字,甚至可以为数组。 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. 请注意,我从AnyObject
更改为Any
因为字符串不是对象。
If you want, you can make both data
and key
optional, too: 如果需要,您也可以将data
和key
设为可选:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.