簡體   English   中英

在 Swift 中創建 CGPoints 數組

[英]Create Array of CGPoints in Swift

我有循環遍歷雙精度數組並從雙精度和數組索引創建 CGPoint 的代碼。

但是,我不知道如何將生成的 CGPoints 放入數組中。 這是我的代碼:

 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 語言指南,值得。

更好的方法是在此處使用Enumeratedmap

let points = closingprices.enumerated().map { CGPoint(x: Double($0 + 1), y: $1) }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM