Consider the following Swift struct and code:
struct Book {
var title: String
var pages: Int
}
let myBook = Book(title: "Swift Guide", pages: 300)
print(myBook.pages)What will be printed?
struct Book { var title: String var pages: Int } let myBook = Book(title: "Swift Guide", pages: 300) print(myBook.pages)
Memberwise initializer sets properties in the order you provide them.
The memberwise initializer automatically creates an initializer with parameters matching the struct's properties. Here, pages is set to 300, so printing myBook.pages outputs 300.
Look at this Swift struct and code:
struct Car {
var brand: String
var year: Int
}
let myCar = Car(brand: "Toyota")What error will this code cause?
struct Car { var brand: String var year: Int } let myCar = Car(brand: "Toyota")
Memberwise initializer requires all properties to be initialized unless default values are provided.
The memberwise initializer expects both brand and year parameters. Omitting year causes a compile-time error about the missing argument.
Examine this Swift code:
struct Person {
var name: String
var age: Int
init(name: String) {
self.name = name
}
}
let p = Person(name: "Anna", age: 25)Why does this code fail to compile?
struct Person { var name: String var age: Int init(name: String) { self.name = name } } let p = Person(name: "Anna", age: 25)
Adding a custom initializer removes the automatic memberwise initializer.
When you add a custom initializer, Swift does not generate the memberwise initializer automatically. So Person(name:age:) does not exist, causing a compile error.
Given this struct:
struct Rectangle {
var width: Double
var height: Double
}Which code correctly creates a Rectangle instance using the memberwise initializer?
struct Rectangle { var width: Double var height: Double }
Memberwise initializer requires parameter labels matching property names.
Option D uses the correct syntax with parameter labels and matching types. Option D misses labels, A uses assignment syntax which is invalid, and D has a type mismatch.
Consider this Swift struct with default values:
struct Laptop {
var brand: String
var ramGB: Int = 8
var storageGB: Int
}
let myLaptop = Laptop(brand: "Apple", storageGB: 256)How many properties does myLaptop have initialized after this code runs?
struct Laptop { var brand: String var ramGB: Int = 8 var storageGB: Int } let myLaptop = Laptop(brand: "Apple", storageGB: 256)
Default values count as initialized properties.
The struct has three properties: brand, ramGB, and storageGB. The memberwise initializer requires brand and storageGB as parameters. ramGB uses its default value 8. So all three properties are initialized.