0

I find some solution have declare cell as "var" other have "let".

var cell : MenuCell? = tableView.dequeueReusableCellWithIdentifier("cell") as! MenuCell!

Which should i use "var" or "let" ?Thanks in advance.

Avijit Nagare
  • 8,482
  • 7
  • 39
  • 68

4 Answers4

1

Use "let" for this... because you not need to change variable value in local method and for let and var concept refer this click here

Community
  • 1
  • 1
Chirag Desai
  • 827
  • 8
  • 13
1

In general if you are not mutating an instance then it should be declared as let

for example, in your case, you will not assign another reference to cell variable.i.e. cell = aNewCell. So you should declare it as let.

Incase you want to mutate it(assign a new reference to it), then declare it as var as shown below.

var cell1 = tableView.dequeueReusableCellWithIdentifier("cell") as! MenuCell
let cell2 = tableView.dequeueReusableCellWithIdentifier("cell") as! MenuCell
cell1 = cell2
san
  • 3,350
  • 1
  • 28
  • 40
  • Value type can never be nil.comparison isn't allowed – Avijit Nagare Jan 29 '16 at 13:25
  • Can you provide the exact line of code at which you are getting this error? Or may be you can post a new question with the code of whole method in which you are getting this error? – san Jan 29 '16 at 13:39
0

let is preferable if you know that you will never change the variable as object of another class if you want to dynamically set the class then use var .

Reshmi Majumder
  • 961
  • 4
  • 15
0

I would recommend use "let" statement as when you are declaring constants you are saying that it won't be reinitialised with other value (I think if you getting cell from dequeueReusableCellWithIdentifier("cell") you won't get it again in this method again). If somewhere you will create any bug that will initialise it again with other value - "let" will show you an error that you are doing something wrong - bug fixed easily, on other hand "var" will take it and go away. Such bugs really hard to find out and it may not appear for huge amount of time.

Thats why approach "Use only that functionality that you need right now" is better than using much more extensioned one just to prevent such bugs.

Also let variable is more optimised so code is working faster than with var variable.

Volodymyr
  • 1,165
  • 5
  • 16