Hi I am relatively new to swift. I am wanting build an array which contains an array of tuples from the string shown below. The count of tuples in each array is not always constant. The final data structure would be: [[(Double, Double)]]
String to be parsed: "((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))"
I was wondering if anyone has any ideas about the best/most efficient way of doing this. I was thinking of iterating through the original string and setting flags by the character encountered. Then building strings for eastings and northings. But I'm not sure if this is the best way and seems overly complicated. Efficiency is a factor as the string can be quite large at times.
--UPDATE This is the code I have so far, which seems to work. Ideas on improvement or a better way are appreciated, as code is a bit messy. Thanks to everyone that has helped so far.
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)