在 swift 中将字符串转换为双精度数

Convert a string to a double in swift

我正在尝试查询我的用户的距离。我可以用这个代码

    PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in

    let query = PFUser.query()

    query?.whereKey("location", nearGeoPoint: geoPoint!, withinKilometers: 1.0)

我想要做的是,当用户设置一个滑块值时,使用该值而不是上面看到的 1.0。我试图用这段代码来做到这一点: 这是滑块代码:

var distanceSearch: String?

 @IBAction func kmSliderValueChanged(sender: UISlider) {

    let kmCurrentValue = Int(sender.value)

    kmLabelUpdate.text = "\(kmCurrentValue)km"

    distanceSearch = "\(kmCurrentValue)"
}

然后是查询行:

query?.whereKey("location", nearGeoPoint: geoPoint!, withinKilometers: distanceSearch!)

它在查询行上返回一个错误:

cannot convert value of type String to expected argument type Double

所以我需要将滑块 kmCurrentValue 转换为双精度,但我不明白如何通过阅读其他 SO 问题来做到这一点。总的来说,我对编码还很陌生。谁能告诉我我需要做什么?

SO convert string to double

Swift 的 Double class 有一个接受字符串参数的构造函数,因此您可以按照 @luk2302 在评论中建议的那样执行 Double(distanceSearch!)

这个结果 returns 是一个 Swift 可选的,但是,因此您应该 Double(distanceSearch!)! 以解包 Double 构造函数返回的可选。看看the Apple documentation on that Double constructor.

只需使用初始化程序将 distanceSearch 转换为 Double

query?.whereKey("location", nearGeoPoint: geoPoint!, withinKilometers: Double(distanceSearch!)!)

有很多方法可以将 String 转换为 Double。您可以使用默认初始化程序:

Double("23.0")

或转换为NSString并使用doubleValue方法。

("23.0" as NSString).doubleValue

当你处理可选的时候,还有一件额外的事情要做。

let str: String? = ...

那你可以试试强行解包:

Double(str!)

但是当你的字符串在 nil 时这会崩溃。比较安全的方法是:

Double(str ?? "0")

这个默认为零。

没有理由采用这种间接方式。滑块本身给你加倍。您不需要将其转换为字符串然后再转换回双精度数。只需使用滑块本身的 value