Swift Variables

Swift Variables

Declare constants with let, variables with var, and use type inference or annotations as needed.


Constants and Variables

Declare constants with let and variables with var.

Constants cannot be reassigned.

Example

let constant = 10
var counter = 0
counter += 1
// constant = 12 // Error if uncommented
print(constant, counter)

This example shows that var can change while let cannot.


Swift Type Inference

Swift infers types automatically when possible, but you can also use annotations for clarity.

Example

let x = 10
let y: Int = 20
print(x, y)

This example shows that Swift infers types automatically when possible, but you can also use annotations for clarity.

Swift Data Types will be covered in more detail in the Swift Data Types chapter.



Optionals

Use ? to declare values that may be nil.

Example

var nickname: String? = nil
nickname = "KJ"
print(nickname ?? "none")

This example shows an optional that may be nil.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *