Biscuit128
Biscuit128

Reputation: 5398

Declaring variables in 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

Upvotes: 8

Views: 38887

Answers (5)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

First it's not Integer, that's the type in Swift but Int.

Using Type Annotation:

var year : Int
year = 2

Using Type Inference:

var year = 2;

Here the type Int is inferred by the compiler during the assignment of the integer literal to the variable year.

Upvotes: 0

Yogendra Singh
Yogendra Singh

Reputation: 2241

In addition if you have created a third party for others and you want a value to enter from user. The you can create variable with the placeholder.

var APIKey: String = <"Place API key here">

Upvotes: -1

AlBlue
AlBlue

Reputation: 24040

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

Upvotes: 19

glyvox
glyvox

Reputation: 58029

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.

Upvotes: 3

Barry Wang
Barry Wang

Reputation: 17

In swift book said that “A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly”. The var year that you first assign it a int type value,so you can't assign another type value to it.

Upvotes: -2

Related Questions