Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Variable Declaration and Initialize

Tags:

swift

Is there a difference between how following bits of code work?

let x: Int = 4

and

let x: Int
x = 4
like image 755
Mig N. Avatar asked Oct 18 '16 13:10

Mig N.


People also ask

How to declare a variable in Swift?

Swift - Variables 1 Variable Declaration. A variable declaration tells the compiler where and how much to create the storage for the variable. 2 Type Annotations. You can provide a type annotation when you declare a variable, to be clear about the kind of values the variable can store. 3 Naming Variables. ... 4 Printing Variables. ...

What is initialization in Swift?

Swift - Initialization. Initial value is initialized for stored property and also for new instances too the values are initialized to proceed further. The keyword to create initialization function is carried out by 'init ()' method. Swift 4 initializer differs from Objective-C that it does not return any values.

How to initialize the stored property values in Swift?

Swift 4 language provides Init () function to initialize the stored property values. Also, the user has provision to initialize the property values by default while declaring the class or structure members.

What is the difference between local and external initializers in Swift?

Local parameter declaration is used to access within the initialize body and external parameter declaration is used to call the initializer. Swift 4 initializers differ from function and method initializer that they do not identify which initializer are used to call which functions.


1 Answers

This one:

let x: Int = 4

creates a non-optional variable x and initialises it to 4. x can be used without issue.

This one:

let x: Int
// Cannot do anything with x yet
x = 4

creates a non-optional variable x with no defined value. It cannot be used without first assigning it to a value, either directly (as in your example) or by the result of some other statement. If you do try and use it, you'll get a compile-time error.

like image 65
Ed King Avatar answered Oct 18 '22 01:10

Ed King