在Swift中将坐标字符串转换为CLLocations数组

时间:2017-04-25 02:50:37

标签: arrays swift cllocation

我有一个字符串,其中包含我需要转换为数组的坐标列表。我尝试let array = Array(coordinates),但它说String不再符合SequenceType。我需要将字符串转换为CLLocations的数组。我试图转换的字符串如下所示:

let coordinates = "[[39.86475483576405,-75.53281903266907], [39.864688955564304,-75.53292632102966], [39.86455719497505,-75.53300142288208], [39.86440072894666,-75.5330228805542], [39.8642689678039,-75.53295850753784], [39.863305456757146,-75.53223967552185], [39.86303369478483,-75.53266882896423]]"

2 个答案:

答案 0 :(得分:3)

该字符串是有效的JSON字符串。

最直接的方法是使用JSONSerialization对字符串进行反序列化,并将结果映射到[CLLocation]

let coordinates = "[[39.86475483576405,-75.53281903266907], [39.864688955564304,-75.53292632102966], [39.86455719497505,-75.53300142288208], [39.86440072894666,-75.5330228805542], [39.8642689678039,-75.53295850753784], [39.863305456757146,-75.53223967552185], [39.86303369478483,-75.53266882896423]]"

if let data = coordinates.data(using: .utf8),
    let jsonArray = try? JSONSerialization.jsonObject(with: data) as? [[Double]] {
    let locationArray  = jsonArray!.map{CLLocation(latitude:$0[0], longitude:$0[1]) }
    print(locationArray)

}

答案 1 :(得分:1)

一种方法是剥离所有括号和空格,然后将逗号分隔的数字拆分成数组。然后将每对数字字符串转换为数字,最后从这对数字中创建CLLocation

// Your string
let coordinates = "[[39.86475483576405,-75.53281903266907], [39.864688955564304,-75.53292632102966], [39.86455719497505,-75.53300142288208], [39.86440072894666,-75.5330228805542], [39.8642689678039,-75.53295850753784], [39.863305456757146,-75.53223967552185], [39.86303369478483,-75.53266882896423]]"
// Remove the brackets and spaces
let clean = coordinates.replacingOccurrences(of: "[\\[\\] ]", with: "", options: .regularExpression, range: nil)
// Split the comma separated strings into an array
let values = clean.components(separatedBy: ",")
var coords = [CLLocation]()
for i in stride(from: 0, to: values.count, by: 2) {
    // Pull out each pair and convert to Doubles
    if let lat = Double(values[i]), let long = Double(values[i+1]) {
        let coord = CLLocation(latitude: lat, longitude: long)
        coords.append(coord)
    }
}