【发布时间】:2026-01-21 18:10:01
【问题描述】:
因此,自从 Swift 3 发布以来,我访问字典的部分代码不再工作,这里是之前版本 swift 的代码:
var locationDict: NSDictionary?//location dictionary
if let getLocation = item.value?["Location"]{locationDict = getLocation as? NSDictionary}
//get dictionary values
let getLatitude = locationDict?.valueForKey("latitude") as! Double
let getLongitude = locationDict?.valueForKey("longitude") as! Double
现在有了新版本,我不知道如何重写“getLocation”。我只用新语法重写了最后两行:
//get dictionary values
let getLatitude = locationDict?.value(forKey: "latitude") as! Double
let getLongitude = locationDict?.value(forKey: "longitude") as!
我正在使用 Firebase,这是完整的功能:(它将一组注释添加到地图)
func setAnnotations(){
//get data
ref.child("Stores").observe(.value, with: { (snapshot) in
self.mapView.removeAnnotations(self.annArray)
for item in snapshot.children {
let annotation = CustomAnnotation()
//set all data on the annotation
annotation.subtitle = (snapshot.value as? NSDictionary)? ["Category"] as? String
annotation.title = (snapshot.value as? NSDictionary)? ["Name"] as? String
annotation.annImg = (snapshot.value as? NSDictionary)? ["Logo"] as? String
var locationDict: NSDictionary?//location dictionary
if let getLocation = item.value?["Location"]{locationDict = getLocation as? NSDictionary}
let getLatitude = locationDict?.value(forKey: "latitude") as! Double
let getLongitude = locationDict?.value(forKey: "longitude") as! Double
annotation.coordinate = CLLocationCoordinate2D(latitude: getLatitude, longitude: getLongitude)
self.annArray.append(annotation)
self.mapView.addAnnotation(annotation)
}
})
}
【问题讨论】:
-
用你的最小 JSON 结构作为文本和你的完整函数更新你的 Q
-
let getLatitude = locationDict?["latitide"] as? Double -
@Dravidian 我添加了这个功能,我正在使用 firebase。
-
不要在 Swift 中使用
NSDictionary。你扔掉类型信息。
标签: swift dictionary firebase firebase-realtime-database