简体   繁体   English

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

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

I am a complete newbie to Swift and didn't found anything on the web. 我是Swift的新手,并没有在网上找到任何东西。 How do I convert a string formatted this way: 如何转换以这种方式格式化的字符串:

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

to an array of CGPoint's ? 到一个CGPoint阵列?

This solution uses the CGPointFromString function provided by iOS. 此解决方案使用iOS提供的CGPointFromString函数。

import UIKit

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

I don't know, something like this? 我不知道,这样的事情?

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)

It's unsafe, of course, and doesn't handle all conditions. 当然,这是不安全的,并不能处理所有条件。 But this should take you in the right direction. 但这应该会带你走向正确的方向。

Here is a more functional way. 这是一种更实用的方式。 Needs error checking added. 需要添加错误检查。

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