[英]How do I swap the first and second items in an array of strings?
我有一个字符串格式的坐标列表,分别有经度和纬度。 我想拥有纬度和经度:
var str = "POLYGON ((-97.7157864909859 30.406523563068, -97.7165355983688 30.4068866173208, -97.7167879301601 30.406495457696, -97.7168046574092 30.4065112735542, -97.7168203607564 30.406527859154, -97.7168349935064 30.4065451649171))
我删除了格式的字符串:
let formattedString = str.replacingOccurrences(of: "POLYGON ((", with: "").replacingOccurrences(of: "))", with: "").replacingOccurrences(of: ",", with: "")
var token = formattedString.components(separatedBy: " ")
现在我试图翻转经度和纬度的位置,以便它:
30.406523563068, -97.7157864909859, 30.4068866173208, -97.7157864909859
我尝试了以下但它似乎没有改变数组的配置:
var coordinateArray = [String]()
for (index, coordinate) in token.enumerated() {
if index % 2 == 0 {
coordinateArray.insert(coordinate, at: index)
} else {
coordinateArray.insert(coordinate, at: index)
}
}
任何帮助将不胜感激。
这是一个更实用的方法:
let str = "POLYGON ((-97.7157864909859 30.406523563068, -97.7165355983688 30.4068866173208, -97.7167879301601 30.406495457696, -97.7168046574092 30.4065112735542, -97.7168203607564 30.406527859154, -97.7168349935064 30.4065451649171))"
let formattedString = str.replacingOccurrences(of: "POLYGON ((", with: "").replacingOccurrences(of: "))", with: "")
// split by commas, not spaces, because in the original string, pairs of
// coordinates are separated by commas
let coordianates = formattedString.components(separatedBy: ", ")
// Here I transform each pair of coordinate into an array with two elements,
// reverse it, and flatten the whole array
let flipped = coordianates.flatMap { $0.components(separatedBy: " ").reversed() }
print(flipped)
您可能想使用swapAt
函数尝试此操作,
var arr = [30.406523563068, -97.7157864909859, 30.4068866173208, -54.881838371711]
for(index, _) in arr.enumerated() {
if index % 2 == 0 && index + 1 < arr.count {
arr.swapAt(index, index + 1)
}
}
print(arr)
使用swapAt(_:_:)
例:
var names = ["Paul", "John", "George", "Ringo"]
names.swapAt(0, 1)
这将在阵列中交换"Paul"
和"John"
。
满足您的特殊需求
var str = "POLYGON ((-97.7157864909859 30.406523563068, -97.7165355983688 30.4068866173208, -97.7167879301601 30.406495457696, -97.7168046574092 30.4065112735542, -97.7168203607564 30.406527859154, -97.7168349935064 30.4065451649171))"
let formattedString = str.replacingOccurrences(of: "POLYGON ((", with: "").replacingOccurrences(of: "))", with: "").replacingOccurrences(of: ",", with: "")
var coordinateArray = formattedString.components(separatedBy: " ")
for i in stride(from: 0, to: coordinateArray.endIndex - 1, by: 2) {
coordinateArray.swapAt(i, i+1)
}
如果您的coordinateArray看起来像这样
[-97, 30, -97, 30]
然后你可以说你要刷每两个元素。 然后你需要stride
方法,它给你数组中每个元素的第二个索引(从0开始),然后你可以使用swapAt
方法,它将每个第二个索引和带有索引的元素交换元素。
for index in stride(from: coordinateArray.startIndex, to: coordinateArray.endIndex - 1, by: 2) {
coordinateArray.swapAt(index, index + 1)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.