![](/img/trans.png)
[英]Programmatically set image to UIImageView with Xcode 6.1/Swift
[英]Swift optional variable not set using Xcode 6.1
我正在尝试构建我的第一个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)
我可以看到我的place对象现在已正确实例化,但是我不明白为什么。 当我尝试保存最近的位置时,我也遇到了完全相同的问题:
closestPlace = place
在检查器中,即使在使用我的place对象设置之后, closestPlace
的值也为零。
我解决了添加问题!
在Place
对象之后。 我想是要告诉我,我确定我在此变量中有一个Object,并且它不是nil。
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")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.