繁体   English   中英

Swift:如何将String列表转换为CGPoint列表?

[英]Swift: How to convert a list of String to a list of CGPoint?

我是Swift的新手,并没有在网上找到任何东西。 如何转换以这种方式格式化的字符串:

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

到一个CGPoint阵列?

此解决方案使用iOS提供的CGPointFromString函数。

import UIKit

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

我不知道,这样的事情?

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)

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

这是一种更实用的方式。 需要添加错误检查。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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