2016-06-14 149 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