Challenge - 5 Problems
Swift Struct Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Look at what property is printed from the struct instance.
✗ Incorrect
The code creates a Person struct with name and age. Printing p.name outputs the string "Anna".
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Check if the struct instance is declared as variable or constant.
✗ Incorrect
Since 'dog' is declared with 'var', its properties can be changed. The age is updated to 6.
❓ Predict Output
advanced2: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())
Attempts:
2 left
💡 Hint
Multiply width and height to get the area.
✗ Incorrect
The area method returns width * height, which is 3 * 4 = 12.
❓ Predict Output
advanced2: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")
Attempts:
2 left
💡 Hint
Check if all stored properties have values after init.
✗ Incorrect
The struct has two stored properties but the init only sets 'model'. 'year' is not initialized, causing a compile error.
🧠 Conceptual
expert2: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)
Attempts:
2 left
💡 Hint
Count how many people have age less than 18.
✗ Incorrect
Jane (17) and Alice (16) are under 18, so 2 items remain after filtering.