1
var occurences: [Int : Int] = [:]  
for number in numbers {  
  if var value = occurences[number] {  
    occurences[number] = ++value  
  } else {  
    occurences[number] = 1
  }  
}

I understand the first 2 lines that it declares an empty dictionary and I have an array of numbers to iterate in a for-in loop, but can someone explain the 4th and 5th line, please. I just don't get how it declares which one is the key and which one is the value. Thank you so much, stucking here for like 2 days.

Knu
  • 14,806
  • 5
  • 56
  • 89
David Zou
  • 11
  • 1

1 Answers1

2

This line

if var value = occurences[number] 

means that it checks to see if occurences has some value stored for key number and then in next line

 occurences[number] = ++value  

it increments the value by using ++ and then saves that to the occurences dict.

Shamas S
  • 7,507
  • 10
  • 46
  • 58
  • 2
    The ++value is going away come swift 3, and should be replaced with value + 1 (and thus also let instead of var). I know, not your code, but worth mentioning as the ++ part is horribly intuitive in this code example! – TofuBeer Jul 12 '16 at 03:10
  • 1
    The same applies to `if var` – Leo Dabus Jul 12 '16 at 03:13
  • @TofuBeer and in that case you will have to do `value += 1` and the (in the next line) `occurences[number] = value` – Alonso Urbano Jul 12 '16 at 04:05
  • 1
    @VladimirNul occurences[number] = value + 1 there is no need for ++ or += at all – TofuBeer Jul 12 '16 at 16:41
  • @TofuBeer You are right, in this case it isn't. I was thinking in a case where value is set outside the loop. – Alonso Urbano Jul 12 '16 at 16:45
  • @Shamas S how do you know that it is asking to check in the key of the dict instead of value? Is it because it is if var VALUE? Can you just name it value cuz it is called value in the dictionary... I kinda get your point but still a a little confused. And one more question, may you just simply explain reduce function, like what does it do. – David Zou Jul 13 '16 at 06:13
  • @DavidZou I think you misunderstood. It's getting the value for they key which in this case is named as `number`. The result is stored in `value`. If the `value` is not zero, `value` is incremented, and then saved back in the dictionary named `occurences` – Shamas S Jul 13 '16 at 06:39