Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables in swift

Tags:

ios

swift

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

enter image description here

like image 453
Biscuit128 Avatar asked Sep 24 '14 10:09

Biscuit128


People also ask

How do you declare a variable in Swift?

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.

How do you declare an int variable in Swift?

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.

How do I declare a variable in Swift 4?

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.

How do I declare multiple variables in Swift?

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.


2 Answers

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/)

like image 187
AlBlue Avatar answered Oct 07 '22 17:10

AlBlue


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.

like image 40
Tamás Sengel Avatar answered Oct 07 '22 16:10

Tamás Sengel