【问题标题】:Create Array of CGPoints in Swift在 Swift 中创建 CGPoints 数组
【发布时间】:2020-07-16 20:11:25
【问题描述】:

我有循环遍历双精度数组并从双精度和数组索引创建 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 放入数组中?

【问题讨论】:

    标签: ios arrays swift cgpoint


    【解决方案1】:

    存在一些问题和不良做法

    你声明的类型是[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 语言指南,这是值得的。

    【讨论】:

    • 谢谢,不知道它知道什么是“索引”
    • 0..&lt;closingprices.count 我建议永远不要使用/教授它。这太容易出错了。
    • @Alexander,您是否在 vadian 的回答中添加了删除线?以前从未见过
    • @user6631314 html 字符串
    • @user6631314 我自己做的。
    【解决方案2】:

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

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

    【讨论】:

    • 优雅的一行。由于解释,我已经将 Vadian 标记为正确,但这是一个很好的方法。
    • @user6631314 您可以使用任何您喜欢的方法,一切正常。在可用时使用高阶函数是更快捷的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多