2016-06-14 148 views
1

我是一个Swift的新手,并没有在网上找到任何东西。如何转换格式为这样的字符串:Swift:如何将String列表转换为CGPoint列表?

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

要CGPoint的数组?

+1

分解成问题:解析字符串转换为字符串的部分,这些部分转换为数字,然后转换那些CGPoint – Alexander

+0

我很好奇,你得到了 – Alexander

+0

@AMomchilov这些非常格式的字符串:这是从* .tmx文件,用xml格式化的瓦片贴图。 – salocinx

回答

5

该解决方案使用iOS提供的CGPointFromString功能。

import UIKit 

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

谢谢 - 也是一个非常性感的选择:-)! – salocinx

+0

@appzYourLife你是一个人! – Alexander

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) 

当然,它是不安全的,并且不处理所有条件。但是,这应该带你走向正确的方向。

+0

非常感谢!一个非常好的起点,正是我需要的:-) – salocinx

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) 
+0

非常好:-)!谢谢。 – salocinx

+0

记住错误句柄。拆分可能会破坏格式不正确,字符串可能无法通过“Int”初始化程序等解释。 – Alexander