就像@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
希望这可以帮助^^