[英]How to transpose a list of CGPoints into a Swift array
I have a (list) of CGPoints returned in the format below (with line feeds ("/n") on each line):我有一个(列表)以下面的格式返回的 CGPoints(每行都有换行符(“/n”)):
80.0 (return)
100.0 (return)
120.0 (return)
150.0 (return)
I wish to transpose the above CGPoint
(Doubles) (list) into a Swift (Integer) array [80,100,120,140]
using this Swift statement: Array(arrayLiteral: list)
:我希望使用以下 Swift 语句将上述
CGPoint
(Double) (list) 转换为 Swift (Integer) 数组[80,100,120,140]
: Array(arrayLiteral: list)
:
But first I must convert the line feeds (return "/n"
) to commas ( ","
) using this Swift RegEx statement below, which is not working for some reason:但首先我必须使用下面的这个 Swift RegEx 语句将换行符(返回
"/n"
)转换为逗号( ","
),这由于某种原因不起作用:
let wantedList = list.replacingOccurrences(of: "\n", with: ",",options: .regularExpression)
Any suggestions where:任何建议:
a) I am screwing up in this RegEx conversion? a) 我在这个 RegEx 转换中搞砸了? b) Some way to do a one-pass transposition to get the desired array of
CGPoints
in the form of [80,100,120,140]
b) 某种方式进行一次转置以获得
[80,100,120,140]
形式的所需CGPoints
数组
Clarification:澄清:
Many thanks: worked like a charm when passing in the raw CGPoints between a string literal (""") ! In my particular case: I am passing in my CGPoints in the form of a string variable: let list = "(frame.origin.y)" ). I cannot figure out how to insert the required double quotes at the beginning and end of this list variable so I keep getting back each CGPoint as an individual array ie [80][100] rather than as a fully populated array [80,100,120,140]
.非常感谢:在字符串文字 (""") 之间传递原始 CGPoints 时,它就像一个魅力!在我的特殊情况下:我以字符串变量的形式传递我的 CGPoints: let list = "(frame.origin .y)" )。我不知道如何在这个列表变量的开头和结尾插入所需的双引号,所以我一直把每个 CGPoint 作为一个单独的数组,即 [80][100] 而不是一个完全填充的数组数组
[80,100,120,140]
。
You can split your string into lines and compact map the substrings up to the first space trying to initialize a Double:您可以将字符串拆分为行并将子字符串压缩映射到尝试初始化 Double 的第一个空格:
let string = """
80.0 (return)
100.0 (return)
120.0 (return)
150.0 (return)
"""
let values = string.split(whereSeparator: \.isNewline)
.compactMap {
Double($0[..<($0.firstIndex(of: " ") ?? $0.endIndex)])
}
print(values) // "[80.0, 100.0, 120.0, 150.0]\n"
If you would like integers instead of Doubles just try to find a period instead of a space:如果您想要整数而不是双精度数,请尝试查找句点而不是空格:
let integers = string.split(whereSeparator: \.isNewline)
.compactMap {
Int($0[..<($0.firstIndex(of: ".") ?? $0.endIndex)])
}
print(integers) // "[80, 100, 120, 150]\n"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.