Browse Questions
  • They're often confused because both involve "hiding" something, but they hide different things for different reasons: - Encapsulation hides internal state to protect it from invalid mutation (an…
  • Classic OOP centers on classes and inheritance hierarchies — behavior is shared by subclassing a base class.
  • Use separate Xcode Schemes, Build Configurations, Bundle Identifiers, and Firebase plists — one set per environment.
  • A Singleton ensures only one instance of a class exists globally.

Answer: They're often confused because both involve "hiding" something, but they hide different things for different reasons:

  • Encapsulation hides internal state to protect it from invalid mutation (an implementation detail / data-integrity concern).
  • Abstraction hides implementation complexity behind a simpler interface, so callers depend on what something does, not how (a design / interface concern).
protocol ImageLoader {
    func load(url: URL) async throws -> UIImage
}

// Caller only knows the abstraction...
func showAvatar(loader: ImageLoader, url: URL) async {
    let image = try? await loader.load(url: url)
}

// ...not that this implementation encapsulates a cache and a URLSession
final class CachingImageLoader: ImageLoader {
    private var cache: [URL: UIImage] = [:]   // encapsulated state
    private let session = URLSession.shared

    func load(url: URL) async throws -> UIImage {
        if let cached = cache[url] { return cached }
        let (data, _) = try await session.data(from: url)
        let image = UIImage(data: data)!
        cache[url] = image
        return image
    }
}