Search code examples
iosarraysswiftcgpoint

Create Array of CGPoints in Swift


I have code that loops through an array of doubles and creates a CGPoint from the double and the index of the array.

However, I can't figure out how to place the resulting CGPoints into an array. Here is my code:

 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
    }

How can I place the CGPoints into an array?


Solution

  • There are a few issues and bad practices

    You are declaring the type [CGPoint].self, an empty array is

    var points = [CGPoint]()
    

    A much better way in Swift is a for loop

    for i in 0..<closingprices.count {
       points.append(CGPoint(x: Double(i+1),y: closingprices[i])) 
    }
    

    or (preferred) Fast Enumeration

    for (index, price) in closingprices.enumerated() {
       points.append(CGPoint(x: Double(index+1),y: price)) 
    }
    

    Please read the Swift Language Guide, it's worth it.