嗨,我对swift相对较新。我想要构建一个数组,其中包含来自下面显示的字符串的元组数组。每个数组中元组的数量并不总是恒定的。最终的数据结构是: [[(Double,Double)]]
要解析的字符串: “((2363448.9 5860581.3,2363438.0 5860577.9),(2363357.5 5860494.7,2363303.2 5860502.0,2363282.5 5860502.5),(2363357.5 5860494.7),(......... etc))”
我想知道是否有人对最佳/最有效的方式有任何想法。我正在考虑迭代原始字符串并按遇到的字符设置标记。然后为东边和北边建造弦乐。但我不确定这是不是最好的方式,看起来过于复杂。 效率是一个因素,因为字符串有时可能非常大。
- UPDATE 这是我到目前为止的代码,似乎有效。对改进的想法或更好的方法表示赞赏,因为代码有点混乱。感谢迄今为止帮助过的所有人。
typealias Coordinate = (easting: Double, northing: Double)
typealias Coordinates = [[Coordinate]]
var array = Array<Array<Coordinate>>() //Array of array of tuples(Double)
var tupleArray = [Coordinate]() //Array of tuples(Double)
var tuple: (Double, Double)! = (0, 0)
var easting: Bool = false
var northing: Bool = false
var eastingString: String = ""
var northingString: String = ""
var openBracket = 0
let tempString = getSubstringFromIndex(wktGeometry , character: "G") //string to parse
for char in tempString.characters {
if char == "(" {
openBracket++
if openBracket == 2 {
easting = true
}
} else if char == ")" {
openBracket--
if openBracket == 1 {
tuple.1 = Double(northingString)!
tupleArray.append(tuple)
array.append(tupleArray)
tupleArray = [Coordinate]()
eastingString = ""
northingString = ""
}
} else if char == "," {
if openBracket == 2 {
tuple.1 = Double(northingString)!
tupleArray.append(tuple)
eastingString = ""
northingString = ""
}
} else if char == " " {
if easting == true {
tuple.0 = Double(eastingString)!
easting = false
northing = true
} else {
northing = false
easting = true
}
} else {
if easting {
eastingString += String(char)
} else if northing {
northingString += String(char)
}
} //end if
} //end for
print(array)
答案 0 :(得分:1)
您的代码问题在于您尝试一次完成所有操作。如果将任务拆分为小的子任务,它将变得更加简单:
// will parse "2363448.9 5860581.3"
func parseCoordinate(coordinateString: String) -> (Double, Double) {
// possible implementation:
// 1. split string by space,
// 2. assert there are two components
// 3. parse them to Doubles and return them
}
// will parse "(2363448.9 5860581.3, 2363438.0 5860577.9)"
func parseCoordinates(coordinatesString: String) -> [(Double, Double)] {
// possible implementation:
// 1. remove last character "(" and end character ")"
// 2. split the string by "," + remove spaces around results
// 3. call parseCoordinate for every result (e.g. using "map" method)
}
// will parse your whole string
func parse(string: String) -> [[(Double, Double)]] {
// possible implementation
// 1. Use a smart regular expression to split by "," not inside "(" and ")" or just by string "), ("
// 2. call parseCoordinates for every result (e.g. using "map" method)
}
最重要的是:
Array.map
方法答案 1 :(得分:-1)
基本上[[2363448.9 5860581.3, 2363438.0 5860577.9], [2363357.5 5860494.7, 2363303.2 5860502.0], [2363282.5 5860502.5, 2363357.5 5860494.7]]
将使用上面提到的trojanfoe的JSON代码。除此之外,您可以使用变量来存储它们,并在使用追加时添加它们。它肯定看起来更干净,除非你拥有的是一个常数。