Bird
Raised Fist0
iOS Swiftmobile~20 mins

Variables (let, var) and type inference in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Simple Info Screen
This screen shows a greeting message and a number. It uses variables and constants with type inference.
Target UI
-------------------------
| Simple Info Screen     |
|-----------------------|
| Greeting: Hello, User! |
| Number: 42             |
|                       |
| [Change Number Button] |
-------------------------
Use let to declare a constant greeting message with type inference.
Use var to declare a variable number with type inference.
Display the greeting and number on the screen.
Add a button labeled 'Change Number' that changes the number variable to a new value when tapped and updates the display.
Starter Code
iOS Swift
import SwiftUI

struct ContentView: View {
    // TODO: Declare greeting constant here
    
    // TODO: Declare number variable here
    
    var body: some View {
        VStack(spacing: 20) {
            // TODO: Show greeting text
            
            // TODO: Show number text
            
            Button("Change Number") {
                // TODO: Change number variable to a new value
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
import SwiftUI

struct ContentView: View {
    let greeting = "Hello, User!"
    @State private var number = 42
    
    var body: some View {
        VStack(spacing: 20) {
            Text("Greeting: \(greeting)")
                .font(.title2)
            Text("Number: \(number)")
                .font(.title3)
            Button("Change Number") {
                number = 100
            }
            .buttonStyle(.borderedProminent)
        }
        .padding()
    }
}

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

We use let to declare greeting as a constant string. This means its value cannot change.

We use @State var number to declare a variable that can change and update the UI when it does.

The Text views show the greeting and number. The button changes the number from 42 to 100 when tapped, and the UI updates automatically because number is a state variable.

This example shows how Swift infers types from the assigned values, so we don't need to write String or Int explicitly.

Final Result
Completed Screen
-------------------------
| Simple Info Screen     |
|-----------------------|
| Greeting: Hello, User! |
| Number: 42             |
|                       |
| [Change Number Button] |
-------------------------
When the user taps the 'Change Number' button, the number changes from 42 to 100 on the screen.
Stretch Goal
Add a second button labeled 'Reset Number' that sets the number back to 42 when tapped.
💡 Hint
Add another Button below the first one. In its action, set the number variable back to 42.

Practice

(1/5)
1. What does the keyword let do in Swift?
easy
A. Creates a constant that cannot be changed
B. Creates a variable that can be changed
C. Declares a function
D. Defines a class

Solution

  1. Step 1: Understand let usage

    The keyword let is used to declare constants in Swift, which means their value cannot be changed after assignment.
  2. Step 2: Compare with var

    Unlike var, which declares variables that can change, let makes the value fixed.
  3. Final Answer:

    Creates a constant that cannot be changed -> Option A
  4. Quick Check:

    let = constant [OK]
Hint: Remember: let = fixed value, var = changeable value [OK]
Common Mistakes:
  • Confusing let with var
  • Thinking let allows value changes
  • Mixing let with function declaration
2. Which of the following is the correct way to declare a variable named score with initial value 10 in Swift?
easy
A. let score = 10
B. var score = 10
C. score var = 10
D. variable score = 10

Solution

  1. Step 1: Identify variable declaration syntax

    In Swift, var is used to declare variables that can change, and the syntax is var name = value.
  2. Step 2: Check each option

    var score = 10 uses correct syntax. let score = 10 declares a constant, not a variable. score var = 10 and variable score = 10 are invalid syntax.
  3. Final Answer:

    var score = 10 -> Option B
  4. Quick Check:

    Variable declaration = var name = value [OK]
Hint: Use var for variables, let for constants [OK]
Common Mistakes:
  • Using let instead of var for variables
  • Incorrect keyword order
  • Using non-existent keywords like variable
3. What will be the output of this Swift code?
var name = "Alice"
name = "Bob"
print(name)
medium
A. Error: Cannot assign to let constant
B. Alice
C. Bob
D. nil

Solution

  1. Step 1: Understand variable reassignment

    The variable name is declared with var, so it can be changed after initial assignment.
  2. Step 2: Trace the code execution

    Initially, name is "Alice". Then it is reassigned to "Bob". The print statement outputs the current value, "Bob".
  3. Final Answer:

    Bob -> Option C
  4. Quick Check:

    var allows change, so output is reassigned value [OK]
Hint: var means value can change, so print latest value [OK]
Common Mistakes:
  • Thinking let was used and reassignment causes error
  • Expecting original value to print
  • Confusing variable with constant
4. What is wrong with this Swift code?
let age = 25
age = 30
medium
A. Cannot assign to value: 'age' is a constant
B. Missing semicolon after 25
C. Variable 'age' not declared
D. Syntax error: let cannot be used

Solution

  1. Step 1: Identify declaration type

    age is declared with let, making it a constant.
  2. Step 2: Understand reassignment error

    Trying to assign a new value to a constant causes a compile-time error: "Cannot assign to value: 'age' is a constant".
  3. Final Answer:

    Cannot assign to value: 'age' is a constant -> Option A
  4. Quick Check:

    let constants cannot be changed [OK]
Hint: let means constant; reassignment causes error [OK]
Common Mistakes:
  • Thinking semicolon is required
  • Confusing let with var
  • Ignoring reassignment rules
5. Consider this Swift code:
var x = 5
let y = x
x = 10
print(y)

What will be printed and why?
hard
A. 10, because y tracks x's value
B. nil, because y is not initialized
C. Error, cannot assign var to let
D. 5, because y is a constant copy of x's initial value

Solution

  1. Step 1: Understand value assignment

    Variable x is 5 initially. y is a constant assigned the current value of x, which is 5.
  2. Step 2: Reassign x and check y

    Changing x to 10 does not affect y, because y holds its own copy of the value 5.
  3. Final Answer:

    5, because y is a constant copy of x's initial value -> Option D
  4. Quick Check:

    let copies value; later changes to var don't affect it [OK]
Hint: let copies value at assignment; later var changes don't affect it [OK]
Common Mistakes:
  • Thinking y updates when x changes
  • Expecting runtime error on assignment
  • Confusing reference and value types
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard