salocinx salocinx - 5 months ago 29
iOS Question

Swift: How to convert a list of strings to a list of CGPoint?

I am a complete newbie to Swift and didn't found anything on the web. How do I convert a string formatted this way:

let str:String = "0,0 624,0 624,-48 672,-48 672,192"


to an array of CGPoint's ?

Answer

I don't know, something like this?

let str:String = "0,0 624,0 624,-48 672,-48 672,192"

let pointsStringArray = str.componentsSeparatedByString(" ")
var points = [CGPoint]()
for pointString in pointsStringArray {
    let xAndY = pointString.componentsSeparatedByString(",")
    let xString = xAndY[0]
    let yString = xAndY[1]
    let x = Double(xString)!
    let y = Double(yString)!
    let point = CGPoint(x: x, y: y)
    points.append(point)
}
print(points)

It's unsafe, of course, and doesn't handle all conditions. But this should take you in the right direction.