0
0
iOS Swiftmobile~5 mins

Variables (let, var) and type inference in iOS Swift

Choose your learning style9 modes available
Introduction

Variables store information you want to use later. Using let and var helps you keep your data safe and clear.

When you want to keep a value that never changes, like your app's name.
When you need to store user input that can change, like a score or a name.
When you want Swift to guess the type of your data to write less code.
When you want to avoid mistakes by making some values constant.
When you want to update a value many times during your app's use.
Syntax
iOS Swift
let constantName: Type = value
var variableName: Type = value

// Or with type inference:
let constantName = value
var variableName = value

let creates a constant that cannot change after it is set.

var creates a variable that can change its value later.

Examples
This creates a constant pi with type Double that cannot change.
iOS Swift
let pi: Double = 3.14159
This creates a variable score with type Int that can change.
iOS Swift
var score: Int = 0
Swift guesses name is a String because of the value.
iOS Swift
let name = "Alice"
Swift guesses isLoggedIn is a Bool because of the value.
iOS Swift
var isLoggedIn = false
Sample App

This SwiftUI app shows a score that starts at 0 and can increase by pressing a button. The max score is a constant that never changes.

iOS Swift
import SwiftUI

struct ContentView: View {
    @State private var score = 0
    let maxScore = 10

    var body: some View {
        VStack(spacing: 20) {
            Text("Score: \(score)")
                .font(.largeTitle)
            Button("Increase Score") {
                if score < maxScore {
                    score += 1
                }
            }
            Text("Max score is fixed at \(maxScore)")
                .foregroundColor(.gray)
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
OutputSuccess
Important Notes

Use let whenever you know the value won't change to avoid bugs.

Swift's type inference helps you write less code but you can always specify types if you want.

Changing a let constant after setting it will cause an error.

Summary

let creates constants that cannot change.

var creates variables that can change.

Swift can guess the type of a variable or constant from its value.