Reputation: 111
I'm new to Swift and I am confused about the following:
In the lines Int(something)
and var x :Int = something
, what is the difference between Int()
and :Int
?
Upvotes: 1
Views: 2454
Reputation: 72780
From a pure language perspective, the correct way to assign a value to an integer (or other numerical types) variable is:
let num = Int(16)
or any of its variants.
However Swift implements some syntactic sugar to make that less verbose - thanks to which you can rewrite the above statement as:
let num = 16
which is equivalent to:
let num: Int = 16
(thanks to type inference)
This is possible because the Int
type implements the IntegerLiteralConvertible
protocol, and by doing that the compiler is able to translate an integer literal into an initializer invocation.
There are several other protocols like that, for string, array, float, etc.
If you want to know more, I recommend reading Swift Literal Convertibles at NSHipster.
If you are wondering if you can do that on your own classes/structs, the answer is yes - you just have to implement the protocol corresponding to the literal type you want to use.
Upvotes: 1
Reputation: 285250
In fact var x = Int(something)
and var x : Int = something
is exactly the same.
Unlike in Objective-C where int
is a scalar type Int
in Swift ist a struct and
structs must be initialized.
The former syntax is an explicit call of the initializer, the latter an implicit call by assigning the value
Upvotes: 4