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.

PillarWhat it meansSwift example
EncapsulationHide internal state, expose controlled accessprivate(set) var balance
AbstractionExpose what something does, not howprotocol PaymentProcessor
InheritanceReuse/extend behavior from a base typeclass SavingsAccount: Account
PolymorphismSame 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