在 Swift 中创建 CGPoints 数组
Create Array of CGPoints in Swift
我有循环遍历双精度数组并根据双精度和数组索引创建 CGPoint 的代码。
但是,我不知道如何将生成的 CGPoint 放入数组中。这是我的代码:
var points = [CGPoint].self//The compiler is okay with this but I don't know what self really means. Without self it giver error 'expected member name or constructor call after type name'
var i:Int = 0
while i < closingprices.count {
let mypoint = CGPoint(x: Double(i+1),y: closingprices[i])
// points += mypoint //This throws error:Binary operator '+=' cannot be applied to operands of type '[CGPoint].Type' and 'CG
i+=1
}
如何将 CGPoints 放入数组中?
存在一些问题和不良做法
你声明的类型是[CGPoint].self
,一个空数组是
var points = [CGPoint]()
Swift 中更好的方法是 for
循环
for i in 0..<closingprices.count {
points.append(CGPoint(x: Double(i+1),y: closingprices[i]))
}
或(首选)快速枚举
for (index, price) in closingprices.enumerated() {
points.append(CGPoint(x: Double(index+1),y: price))
}
请阅读 Swift 语言指南,这是值得的。
更好的方法是在此处使用 Enumerated
和 map
。
let points = closingprices.enumerated().map { CGPoint(x: Double([=10=] + 1), y: ) }
我有循环遍历双精度数组并根据双精度和数组索引创建 CGPoint 的代码。
但是,我不知道如何将生成的 CGPoint 放入数组中。这是我的代码:
var points = [CGPoint].self//The compiler is okay with this but I don't know what self really means. Without self it giver error 'expected member name or constructor call after type name'
var i:Int = 0
while i < closingprices.count {
let mypoint = CGPoint(x: Double(i+1),y: closingprices[i])
// points += mypoint //This throws error:Binary operator '+=' cannot be applied to operands of type '[CGPoint].Type' and 'CG
i+=1
}
如何将 CGPoints 放入数组中?
存在一些问题和不良做法
你声明的类型是[CGPoint].self
,一个空数组是
var points = [CGPoint]()
Swift 中更好的方法是 for
循环
for i in 0..<closingprices.count {
points.append(CGPoint(x: Double(i+1),y: closingprices[i]))
}
或(首选)快速枚举
for (index, price) in closingprices.enumerated() {
points.append(CGPoint(x: Double(index+1),y: price))
}
请阅读 Swift 语言指南,这是值得的。
更好的方法是在此处使用 Enumerated
和 map
。
let points = closingprices.enumerated().map { CGPoint(x: Double([=10=] + 1), y: ) }