我是Swift的新手,并没有在网上找到任何东西。如何转换以这种方式格式化的字符串:
let str:String = "0,0 624,0 624,-48 672,-48 672,192"
到CGPoint的数组?
答案 0 :(得分:6)
此解决方案使用iOS提供的CGPointFromString
功能。
import UIKit
let res = str
.components(separatedBy: " ")
.map { CGPointFromString("{\($0)}") }
答案 1 :(得分:1)
我不知道,这样的事情?
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)
当然,它不安全,并且不能处理所有条件。但这应该会让你朝着正确的方向前进。
答案 2 :(得分:1)
这是一种更实用的方式。需要添加错误检查。
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)