gpt4 book ai didi

arrays - 在 Swift 中将坐标字符串转换为 CLLocation 数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:16:34 25 4
gpt4 key购买 nike

我有一个包含坐标列表的字符串,我需要将其转换为数组。我尝试执行 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]]"

最佳答案

该字符串是一个有效的 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)

}

关于arrays - 在 Swift 中将坐标字符串转换为 CLLocation 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43600762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com