我是一个Swift的新手,并没有在网上找到任何东西。如何转换格式为这样的字符串:Swift:如何将String列表转换为CGPoint列表?
let str:String = "0,0 624,0 624,-48 672,-48 672,192"
要CGPoint的数组?
我是一个Swift的新手,并没有在网上找到任何东西。如何转换格式为这样的字符串:Swift:如何将String列表转换为CGPoint列表?
let str:String = "0,0 624,0 624,-48 672,-48 672,192"
要CGPoint的数组?
我不知道,像这样?
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)
当然,它是不安全的,并且不处理所有条件。但是,这应该带你走向正确的方向。
非常感谢!一个非常好的起点,正是我需要的:-) – salocinx
这是一个更加实用的方法。需要添加错误检查。
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)
分解成问题:解析字符串转换为字符串的部分,这些部分转换为数字,然后转换那些CGPoint – Alexander
我很好奇,你得到了 – Alexander
@AMomchilov这些非常格式的字符串:这是从* .tmx文件,用xml格式化的瓦片贴图。 – salocinx