DevPrep

All topics › Programming basics

Abstraction

Junior

Essence

Abstraction is singling out what matters and hiding the details. In code it means working with a contract ("can save a token") rather than a concrete implementation ("writes to the Keychain via SecItemAdd"). The code then depends on a stable interface, while the implementation can be changed, swapped and tested separately.

In Swift the main abstraction tool is the protocol. The language has no abstract classes; protocols with default implementations in an extension play that role.

Example: a storage abstraction

protocol TokenStorage {
    func save(_ token: String) throws
    func load() throws -> String?
}

struct KeychainStorage: TokenStorage {  // production: Security.framework
    func save(_ token: String) throws { /* SecItemAdd ... */ }
    func load() throws -> String? { nil /* SecItemCopyMatching ... */ }
}

final class InMemoryStorage: TokenStorage {     // tests: no Keychain
    private var token: String?
    func save(_ token: String) throws { self.token = token }
    func load() throws -> String? { token }
}

final class AuthService {
    private let storage: any TokenStorage       // depends on the abstraction
    init(storage: any TokenStorage) { self.storage = storage }
    func logIn(token: String) throws { try storage.save(token) }
}

AuthService knows nothing about the Keychain. In tests we inject InMemoryStorage, in production KeychainStorage, and tomorrow a server-side store. This is dependency inversion: the high-level module depends on a protocol, not on details.

Levels of abstraction in Swift

How it differs from encapsulation

Abstraction is about the interface: what is visible from outside. Encapsulation is about hiding: private and access boundaries that stop you bypassing the interface. They work together: the protocol defines the abstraction, private protects the implementation.

What the interviewer looks for

Not a textbook definition, but the ability to show a protocol + two implementations + dependency injection and explain why (testability, swapping implementations, isolation from third-party SDKs).

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store