Browse Questions
- These four declarations differ in two dimensions: whether the array itself is optional, and whether the elements inside are optional.
- An iOS app moves through states managed by UIApplicationDelegate (UIKit) or @main + scene lifecycle (SwiftUI/iOS 13+).
- Most candidates fail coding interviews not because they can't code, but because they lack a structured thinking process.
- - Inheritance — a class derives behaviour from a parent class ("is-a" relationship) - Composition — a type gets behaviour by holding references to other objects ("has-a" relationship) Swift…
Answer:
- Inheritance — a class derives behaviour from a parent class ("is-a" relationship)
- Composition — a type gets behaviour by holding references to other objects ("has-a" relationship)
Swift favours composition through protocols and protocol extensions.
Code Example:
// ❌ Inheritance — rigid, can't mix and match
class Animal {
func breathe() { }
}
class Dog: Animal {
func bark() { }
}
class FlyingDog: Dog { } // gets everything even if unneeded
// ✅ Composition — flexible, modular
protocol Breathable { func breathe() }
protocol Swimmable { func swim() }
protocol Flyable { func fly() }
struct Duck: Breathable, Swimmable, Flyable {
func breathe() { }
func swim() { }
func fly() { }
}
// Protocol extensions provide default implementations
extension Swimmable {
func swim() { print("Splashing...") }
}