Protocols with associated types let you define a blueprint with a placeholder type. This helps write flexible and reusable code that works with different data types.
0
0
Protocol with associated types in Swift
Introduction
When you want a protocol to work with different types but keep the type consistent inside each use.
When creating generic collections or containers that can hold any type but must be consistent.
When defining interfaces for algorithms that work on various data types.
When you want to enforce that a type used inside a protocol is specified by the conforming type.
Syntax
Swift
protocol ProtocolName { associatedtype TypeName func someFunction(param: TypeName) }
associatedtype declares a placeholder type inside the protocol.
The actual type is specified by the type that adopts the protocol.
Examples
This protocol defines a container that can hold items of any type. The type is called
Item and is set by the conforming type.Swift
protocol Container { associatedtype Item mutating func append(_ item: Item) var count: Int { get } subscript(i: Int) -> Item { get } }
This struct conforms to
Container and sets Item to Int.Swift
struct IntStack: Container { var items = [Int]() mutating func append(_ item: Int) { items.append(item) } var count: Int { items.count } subscript(i: Int) -> Int { items[i] } }
Sample Program
This program shows a protocol with an associated type Number. Two structs conform to it, one for Int and one for Double. Each sums two numbers of its type.
Swift
protocol Summable { associatedtype Number func sum(_ a: Number, _ b: Number) -> Number } struct IntSummer: Summable { func sum(_ a: Int, _ b: Int) -> Int { return a + b } } struct DoubleSummer: Summable { func sum(_ a: Double, _ b: Double) -> Double { return a + b } } let intSummer = IntSummer() print(intSummer.sum(3, 4)) let doubleSummer = DoubleSummer() print(doubleSummer.sum(2.5, 3.5))
OutputSuccess
Important Notes
Protocols with associated types cannot be used as types directly without specifying the associated type.
Use some ProtocolName or generics to work with protocols with associated types.
Summary
Protocols with associated types let you write flexible blueprints with placeholder types.
The actual type is decided by the conforming type.
This helps create reusable and type-safe code.