1

I have the following for loop in Objective C code and am trying to transfer it to Swift.

double lastAx[4],lastAy[4],lastAz[4];
for (int i = 0; i < 4; ++i){
lastAx[i] = lastAy[i] = lastAz[i] = 0;
}

My Code so far gives me the error: Type Double has no subscript members

var lastAx:Double = 4
var lastAy:Double = 4
var lastAz:Double = 4

    for i: Int32 in 0  ..< 4  {
        lastAx[i] = lastAy[i] = lastAz[i] = 0
    }

What am I missing? Help is very appreciated.

David Seek
  • 16,783
  • 19
  • 105
  • 136

1 Answers1

3

Declare lastAx, lastAy, lastAz as arrays with init(count:repeatedValue:) initializer:

var lastAx = [Double](count:4, repeatedValue: 0)
var lastAy = [Double](count:4, repeatedValue: 0)
var lastAz = [Double](count:4, repeatedValue: 0)

Also you will not have to zero them because these initializers set all of the values to zeros. You won't need the loop from the original code, so just delete it.

vacawama
  • 150,663
  • 30
  • 266
  • 294
Avt
  • 16,927
  • 4
  • 52
  • 72
  • first of all: thank you, but this gives me: `Cannot subscript a value of type '[Double]' with an index of type 'Int32'` – David Seek Apr 27 '16 at 13:08
  • This is because in Swift array's index has type Int (64-bit signed integer), not Int32. Just remove `: Int32` in your code. And you do not need to nullify arrays at all since they are nullified during initialization (see `repeatedValue` option). – Avt Apr 27 '16 at 13:13
  • deleting the `: Int32`gave me: `Cannot assign value of type '()' to type 'Double'` – David Seek Apr 27 '16 at 13:14
  • and with nillify you mean deleteting the `= 0` ? – David Seek Apr 27 '16 at 13:15
  • vacawama changes did deleted the `; needed` error. thank you. but still: `Cannot assign value of type '()' to type 'Double'` – David Seek Apr 27 '16 at 13:18
  • @DavidSeek, does your code match the updated code in the answer? That should work for you. – vacawama Apr 27 '16 at 13:23
  • You receive this error because Swift does not support Multiple variable assignment http://stackoverflow.com/questions/26155523/multiple-variable-assignment-in-swift – Avt Apr 27 '16 at 13:25
  • I have updated my question, so it gets a little more clear. – David Seek Apr 27 '16 at 13:25
  • @Avt okay I see, what are my option to get it working? – David Seek Apr 27 '16 at 13:27
  • @DavidSeek, you don't need the `for` loop from the original code. That was initializing those arrays to zeros, but the initializers in the above answer already do that. Just get rid of the `for` loop and you're done. – vacawama Apr 27 '16 at 13:28
  • ah okay. well. than thank you very much for your effort. @vacawama if you want too, you can summarize your answer, so i can at least give you an upvote. thank you guys – David Seek Apr 27 '16 at 13:31