如何从字符串值Swift中删除Optional

如何从字符串值Swift中删除Optional,第1张

如何从字符串值Swift中删除Optional

就像@GioR所说的那样,该值是Optional(52.523553),因为latstring的类型是隐式的:String?。这是由于let lat =
data.value(forKey:“ lat”)将返回字符串?隐式设置lat的类型。
有关值的文档,请参阅https://developer.apple.com/documentation/objectivec/nsobject/1412591-value(forKey
:)


Swift有多种处理nil的方法。这三个可能对您有帮助,nil合并运算符:

??

如果可选结果为nil,则此运算符将提供默认值:

let lat: String = data.value(forKey: "lat") ?? "the lat in the dictionary was nil!"

警卫声明

guard let lat: String = data.value(forKey: "lat") as? String else {    //Oops, didn't get a string, leave the function!}

Guard语句使您可以将可选变量转换为等效的非可选变量,如果恰好为nil,则可以退出该函数

如果让

if let lat: String = data.value(forKey: "lat") as? String {    //Do something with the non-optional lat}//Carry on with the rest of the function

希望这可以帮助^^



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5020054.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存