Browse Questions
- Classic OOP assumes objects are reference types with identity and shared mutable state.
- Declare a var with a get block that returns the value and a set block that updates the underlying stored state.
- Encapsulation, abstraction, inheritance, and polymorphism.
- Use a protocol for URLSession or inject a custom URLProtocol subclass that intercepts requests and returns fake responses without hitting the network.
Answer: Encapsulation, abstraction, inheritance, and polymorphism. Swift supports all four, though it leans on protocols and value types more than classic class-based OOP languages.
| Pillar | What it means | Swift example |
|---|---|---|
| Encapsulation | Hide internal state, expose controlled access | private(set) var balance |
| Abstraction | Expose what something does, not how | protocol PaymentProcessor |
| Inheritance | Reuse/extend behavior from a base type | class SavingsAccount: Account |
| Polymorphism | Same interface, different underlying behavior | [PaymentProcessor] holding multiple conforming types |
protocol PaymentProcessor {
func charge(_ amount: Decimal) -> Bool
}
class CreditCardProcessor: PaymentProcessor {
func charge(_ amount: Decimal) -> Bool { /* ... */ true }
}
class PayPalProcessor: PaymentProcessor {
func charge(_ amount: Decimal) -> Bool { /* ... */ true }
}
let processors: [PaymentProcessor] = [CreditCardProcessor(), PayPalProcessor()]
processors.forEach { _ = $0.charge(9.99) } // polymorphic dispatch