Back to Swift Reference Ask BeeAI
🔶 Swift LanguageIntermediateSwift 2.0+
Protocols & Protocol Extensions
Define capabilities as contracts, add default behavior with extensions, and use some/any correctly.
A protocol describes what a type can do. Structs, classes and enums can all conform, which enables protocol-oriented design and easy test doubles.
Protocol extensions provide default implementations. Use some Protocol for an opaque concrete type (fast, static dispatch) and any Protocol when you truly need a heterogeneous box.
protocols.swift
1protocol WeatherService {
2 func temperature(in city: String) async throws -> Double
3}
4
5struct LiveWeatherService: WeatherService {
6 func temperature(in city: String) async throws -> Double {
7 // call your API here
8 return 31.5
9 }
10}
11
12struct MockWeatherService: WeatherService {
13 func temperature(in city: String) async throws -> Double { 20 }
14}
15
16extension WeatherService {
17 func summary(for city: String) async -> String {
18 let t = (try? await temperature(in: city)) ?? .nan
19 return "\(city): \(t)°C"
20 }
21}
22
23func makeService(preview: Bool) -> any WeatherService {
24 preview ? MockWeatherService() : LiveWeatherService()
25}Common pitfalls
- Prefer some over any when a single concrete type is returned; any adds boxing and dynamic dispatch.
Still unclear? Ask BeeAI about Protocols & Protocol Extensions.
Get a tailored explanation, or paste your own code for a Swift 6 review. Free members get daily questions — Pro is unlimited.
Related topics
Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.
See Pro Plans