I am trying to follow a tutorial which says if we don't want to initialise a variable in swift we can do the following;
var year:Integer
year = 2;
However, if I declare the above block of code I get an error
"use of undeclared type Integer"
If i use the following instead it works;
var year:integer_t
year = 2;
Why do I need to do this yet the tutorial can use the first method?
Thanks
Edit : screen shot from tutorial
The var keyword is the only way to declare a variable in Swift. The most common and concise use of the var keyword is to declare a variable and assign a value to it. Remember that we don't end this line of code with a semicolon.
Declaring an int variable In Swift, the “var” keyword is used to declare a variable and you don't have to specify the type if it can be inferred from what you're assigning it. Also notice in Swift, we're using the String class as opposed to NSString.
Type Annotations. The following example shows how to declare a variable in Swift 4 using Annotation. Here it is important to note that if we are not using type annotation, then it becomes mandatory to provide an initial value for the variable, otherwise we can just declare our variable using type annotation.
You can declare multiple constants or multiple variables on a single line, separated by commas: var x = 0.0, y = 0.0, z = 0.0.
You need to use an Int, not Integer.
var year:Int
year = 2
Note: You can do this in one line
var year:Int = 2
and use type inference
var year = 2
I've been blogging a little about Swift if you're interested, starting here:
http://alblue.bandlem.com/2014/09/swift-introduction-to-the-repl.html
(You can subscribe to the feed at http://alblue.bandlem.com/Tag/swift/)
If the variable never changes, you should declare a constant instead.
let year: Int = 2
...or with type inference:
let year = 2
Note that Swift infers Int
when you assign a whole number to a variable/constant and Double
when you assign a fraction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With