简体   繁体   中英

Swift: How to convert a list of String 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 ?

This solution uses the CGPointFromString function provided by iOS.

import UIKit

let res = str
    .components(separatedBy: " ")
    .map { CGPointFromString("{\($0)}") }

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.

Here is a more functional way. Needs error checking added.

import Foundation

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

let pointStrings = str.characters //get the character view
                .split{$0 == " "} //split the pairs by spaces
                .map(String.init) //convert the character views to new Strings

let points : [CGPoint] = pointStrings.reduce([]){ //reduce into a new array
                    let pointStringPair = $1.characters
                                            .split{$0 == ","} //split pairs by commas
                                            .map(String.init) //convert the character views to new Strings 
                    let x = CGFloat(Float(pointStringPair[0])!) //get the x
                    let y = CGFloat(Float(pointStringPair[1])!) //get the y
                    return $0 + [CGPoint(x: x, y: y)] //append the new point to the accumulator
                }
print(points)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM