-1

What is the difference between

var button1: UIButton 

and

var button1 = UIButton()

2 Answers2

1

Both of these lines are wrong in terms of Swift.

What you asking is what's the difference between these:

var button1: UIButton = UIButton()
var button1 = UIButton()

Swift has type inference which is basically mechanism that allows to omit the type on declaring a variable if it is initialised. Both of the lines are equal, the second is just makes use of this mechanism.

If you'd try to do something like this

var button2: UIButton = String()

You would get an error because : UIButton is a type annotation for a variable that states "button2 class is UIButton" and you try to assign a String to it.

inokey
  • 5,434
  • 4
  • 21
  • 33
0

var button1: UIButton = UIButton() is "Declared as well as Initialised, explicitly defining its type". Whereas in the second statement var button1 = UIButton() is infered by swift compiler.

If you provide an initial value for a constant or variable at the point that it’s defined, Swift can almost always infer the type to be used for that constant or variable, as described in Type Safety and Type Inference.

Ishika
  • 2,187
  • 1
  • 17
  • 30