【发布时间】:2018-10-30 09:55:36
【问题描述】:
我正在解析一个文本文件以获取位置的纬度和经度。我需要将 lon/lat 字符串转换为双精度,但我做不到。
我已经尝试过 Double(String) 方法和 (String as NSNumber).doubleValue。它总是给出零。
当我手动输入数字时,它会起作用。
这里是sn-p的代码:
var items = [[String]]()
func readParkingData() {
guard let filepath = Bundle.main.path(forResource: "parking", ofType: "txt") else {
print("file not found")
return
}
print("file path : \(filepath)")
do{
let content = try String(contentsOfFile: filepath, encoding: .utf8)
let attributed = content.htmlAttributedString
let decoded : String = attributed!.string
let split = decoded.split(separator: ";")
var count = 0
var item = [String]()
for word in split {
item.append(String(word))
count += 1
if count == 30 {
items.append(item)
item = [String]()
count = 0
}
}
for entry in items {
print(entry[24])
print(entry[25])
let latString : String = entry[24]
let lonString : String = entry[25]
print(type(of: latString))
let lat = Double(latString)
print(lat)
}
}catch{
print("file read error \(filepath)")
}
}
我查看了其他答案。 latString 的类型是 String,不是可选的。修剪空白也无济于事。 lat 始终为零。
这里发生了什么?
【问题讨论】:
-
显示
print(latString.debugDescription)的输出 -
latString.debugDescription 显示 "\"40.426687899755734\""
-
有你的答案:数字用引号括起来。 – 顺便说一句,你为什么对属性字符串而不是原始内容进行操作?输入文件格式是什么?
-
啊当然。感谢那!这是正确的答案。
标签: swift string casting double