Abstraction
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
- Protocols — a behavioural contract;
some Protocol/any Protocolare the ways to refer to it. - Generics — abstraction over a type:
func max<T: Comparable>works with any comparable type. - Types and modules — a module's
publicAPI hides itsinternalimplementation. - Functions — the simplest abstraction: a name instead of a sequence of steps.
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).