-3

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?

user6631314
  • 1,751
  • 1
  • 13
  • 44

2 Answers2

2

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thanks, didn't realize it knows what "index is" – user6631314 Jul 16 '20 at 20:26
  • @Alexander, did you put the strikethrough in vadian's answer? Have never seen that before – user6631314 Jul 16 '20 at 20:36
  • @user6631314 html string – Leo Dabus Jul 16 '20 at 20:38
  • @user6631314 I did it myself. – vadian Jul 16 '20 at 20:39
  • Also nit: this isn't fast enumeration. That's an Objective C thing, with the word "fast" stemming from the fact that multiple items are copied out of an enumerable object at a time. Batching like that reduced the number of message sends required, which spend thing up. In Swift, there no other iteration mechanism built into the language besides for loops which loop over `IteratorProtocol` objects produced by a `Sequence` https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocFastEnumeration.html – Alexander Jul 16 '20 at 21:44
0

A much better approach would be to use Enumerated and map here.

let points = closingprices.enumerated().map { CGPoint(x: Double($0 + 1), y: $1) }
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
  • Elegant one line. I already marked Vadian's correct because of the explanation but this is a nice way to do it. – user6631314 Jul 16 '20 at 20:38
  • @user6631314 You can use any method you like, all works. Using higher-order functions when available is swiftier approach. – Frankenstein Jul 16 '20 at 20:45