Chapter 2 Types, Constants, and Variables Int Declaration


#1

So Xcode runs the same wether you declare 4 an integer, or if you just let Xcode use it’s automatic type selection feature, so why would you add extra lines to your code to declare it an integer?

Programming newbie


#2

By default, Swift assigns the type integer (Int) to numeric literal 4.

Therefore the following two declarations are the same:

var fooBar = 4
var fooBar : Int = 4

Remember that the value of a variable of Int type can be negative.

But if you want to make it clear that the value can’t be negative, then you need to decorate the variable with the explicit type UInt

For example:

var fooBar : UInt = 4

Hope this answers your question.


#3

Partially yes, and Thank you for the reply. But if the two declarations are the same, IE
var fooBar = 4 and var fooBar : Int = 4
is there ever a time when you would actually want to use var fooBar : Int = 4
since it is unnecessary keystrokes?


#4

Yes. For example, when you declare a function that has a default parameter:

func foo (_ bar:Int = 7) -> Int {
    return bar;
}

print (foo ())
print (foo (13))