Browse Questions
- Protocol extensions let you add default implementations to protocol methods, so conforming types get behavior for free without inheriting from a base class.
- @MainActor is a global actor that ensures code runs on the main thread.
- All three separate concerns between data, UI, and logic — but they differ in how the middle layer connects to the view.
- | Problem | Cause | Fix | |---------|-------|-----| | #if SIT always falls through to #else | Flag added to Other Swift Flags instead of Active Compilation Conditions | Move flag to the correct…
Answer: Protocol extensions let you add default implementations to protocol methods, so conforming types get behavior for free without inheriting from a base class.
Code Example:
protocol Greetable {
var name: String { get }
func greet() -> String
}
extension Greetable {
func greet() -> String {
return "Hello, \(name)!"
}
}
struct User: Greetable {
var name: String
// greet() is provided for free by the extension
}
let user = User(name: "Mia")
print(user.greet()) // "Hello, Mia!"
Key Points:
- Enables composition over inheritance
- Multiple protocols can be adopted (vs single class inheritance)
- Constrained extensions let you add methods only for specific types