0
0
Swiftprogramming~20 mins

Struct declaration syntax in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Struct Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple struct instance
What is the output of this Swift code when run?
Swift
struct Person {
    var name: String
    var age: Int
}

let p = Person(name: "Anna", age: 30)
print(p.name)
AAnna
B30
CPerson(name: "Anna", age: 30)
DError: Missing initializer
Attempts:
2 left
💡 Hint
Look at what property is printed from the struct instance.
Predict Output
intermediate
2:00remaining
Value of a struct property after modification
What is the value of the property 'age' after running this Swift code?
Swift
struct Animal {
    var species: String
    var age: Int
}

var dog = Animal(species: "Dog", age: 5)
dog.age = 6
print(dog.age)
A6
B5
CError: Cannot assign to property
D0
Attempts:
2 left
💡 Hint
Check if the struct instance is declared as variable or constant.
Predict Output
advanced
2:00remaining
Output of struct with method
What does this Swift code print?
Swift
struct Rectangle {
    var width: Int
    var height: Int
    func area() -> Int {
        return width * height
    }
}

let rect = Rectangle(width: 3, height: 4)
print(rect.area())
A7
BError: Missing return statement
C12
D0
Attempts:
2 left
💡 Hint
Multiply width and height to get the area.
Predict Output
advanced
2:00remaining
Error raised by incorrect struct declaration
What error does this Swift code produce?
Swift
struct Car {
    var model: String
    var year: Int

    func description() -> String {
        return "Model: \(model), Year: \(year)"
    }
}

let myCar = Car(model: "Tesla")
ANo error, compiles and runs fine
BError: Missing argument for parameter 'year' in call
CError: Cannot assign to property 'model' in initializer
DError: Method description missing return type
Attempts:
2 left
💡 Hint
Check if all stored properties have values after init.
🧠 Conceptual
expert
2:00remaining
Number of items in a struct array after filtering
Given this Swift code, how many items remain in the 'youngPeople' array after filtering?
Swift
struct Person {
    var name: String
    var age: Int
}

let people = [
    Person(name: "John", age: 20),
    Person(name: "Jane", age: 17),
    Person(name: "Bob", age: 25),
    Person(name: "Alice", age: 16)
]

let youngPeople = people.filter { $0.age < 18 }
print(youngPeople.count)
A3
B4
C1
D2
Attempts:
2 left
💡 Hint
Count how many people have age less than 18.