我正在尝试构建我的第一个 Swift 应用程序。在此应用程序中,我正在遍历一个 KML 文件,该文件包含有关某些餐厅的信息,并且我正在尝试为每个餐厅构建一个包含可用信息的 Place
对象,比较距离并保持Place
离给定点最近的地方。
这是我的 Place 模型,一个非常简单的模型 (Place.swift):
import Foundation
import MapKit
class Place {
var name:String
var description:String? = nil
var location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude:0, longitude:0)
init(name: String, description: String?, latitude: Double, longitude: Double)
{
self.name = name
self.description = description
self.location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
func getDistance(point: CLLocationCoordinate2D) -> Float
{
return Geo.distance(point, coordTo: self.location)
}
}
这是循环遍历 KML 文件中项目的应用程序部分。
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
let xml = SWXMLHash.parse(data);
var minDistance:Float = Float(UInt64.max)
var closestPlace:Place? = nil
var place:Place? = nil
for placemark in xml["kml"]["Document"]["Folder"]["Placemark"] {
var coord = placemark["Point"]["coordinates"].element?.text?.componentsSeparatedByString(",")
// Create a place object if the place has a name
if let placeName = placemark["name"].element?.text {
NSLog("Place name defined, object created")
// Overwrite the place variable with a new object
place = Place(name: placeName, description: placemark["description"].element?.text, latitude: (coord![1] as NSString).doubleValue, longitude: (coord![0] as NSString).doubleValue)
var distance = place!.getDistance(self.middlePosition)
if distance < minDistance {
minDistance = distance
closestPlace = place
} else {
NSLog("Place name could not be found, skipped")
}
}
}
我在计算距离时在此脚本中添加了断点。 place
变量的值为 nil,我不明白为什么。如果我替换这一行:
place = Place(name: placeName, description: placemark["description"].element?.text, latitude: (coord![1] as NSString).doubleValue, longitude: (coord![0] as NSString).doubleValue)
通过这一行:
let place = Place(name: placeName, description: placemark["description"].element?.text, latitude: (coord![1] as NSString).doubleValue, longitude: (coord![0] as NSString).doubleValue)
我可以看到我的位置对象现在已正确实例化,但我不明白为什么。 当我试图保存最近的地方时,我也遇到了完全相同的问题:
closestPlace = place
在检查器中,closestPlace
的值即使在用我的位置对象设置后也是 nil。
最佳答案
我在 Place
对象后添加了 !
解决了我的问题。我想是告诉我我确定我在这个变量中有一个对象,它不是零。
if let placeName = placemark["name"].element?.text {
NSLog("Place name defined, object created")
// Overwrite the place variable with a new object
place = Place(name: placeName, description: placemark["description"].element?.text, latitude: (coord![1] as NSString).doubleValue, longitude: (coord![0] as NSString).doubleValue)
var distance = place!.getDistance(self.middlePosition)
if distance < minDistance {
minDistance = distance
closestPlace = place!
} else {
NSLog("Place name could not be found, skipped")
}
}
关于ios - 未使用 Xcode 6.1 设置 Swift 可选变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458129/