我想使用不带可选扩展名的String值。我使用以下代码从firebase解析此数据:
Database.database().reference(withPath: "Locations").child("Cities").observe(.value, with: { (snapShot) in if snapShot.exists() { let array:NSArray = snapShot.children.allObjects as NSArray for child in array { let snap = child as! DataSnapshot let cityName = snap.key let cityNameString = "\(cityName)" if snap.value is NSDictionary { let data:NSDictionary = snap.value as! NSDictionary let lat = data.value(forKey: "lat") let lng = data.value(forKey: "lng") let radius = data.value(forKey: "radius") let latstring = "\(lat)" let lngstring = "\(lng)" let radiusstring = "\(radius)" let city = CityObject(name: cityNameString , lat: latstring , lng: lngstring, radius: radiusstring) print("Value is", laststring) self.selectCity(cityObject: city) } } } })
解析此数据后,我尝试打印例如latstring并得到以下结果:
值是可选的(52.523553)
我的CityObject如下所示:
class CityObject{ var name: String? var lat: String? var lng: String? var radius: String? init(name: String?, lat: String?, lng: String?, radius: String?){ self.name = name self.lat = lat self.lng = lng self.radius = radius }
就像@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
希望这可以帮助^^