Swift Protocol-Oriented Programming
Use when protocol-oriented programming in Swift including protocol extensions, default implementations, protocol composition, associated types, and designing flexible, reusable abstractions that favor composition over inheritance.
What this skill does
# Swift Protocol-Oriented Programming
## Introduction
Protocol-oriented programming (POP) is Swift's paradigm for building flexible,
composable abstractions without the rigid hierarchies of class inheritance.
Protocols define interfaces that types can adopt, while protocol extensions
provide default implementations and capabilities to multiple types
simultaneously.
This approach offers the flexibility of composition, the performance of static
dispatch, and the ability to extend value types like structs and enums. POP is
foundational to Swift's standard library and enables powerful patterns for code
reuse, testing, and API design.
This skill covers protocol design, extensions, associated types, composition,
and practical patterns for building protocol-oriented architectures.
## Protocol Basics and Design
Protocols define contracts that types must fulfill, specifying required
properties, methods, and initializers without providing implementations.
```swift
// Basic protocol definition
protocol Drawable {
var lineWidth: Double { get set }
var color: String { get }
func draw()
mutating func resize(by factor: Double)
}
// Protocol adoption in struct
struct Circle: Drawable {
var lineWidth: Double
let color: String
var radius: Double
func draw() {
print("Drawing circle with radius \(radius)")
}
mutating func resize(by factor: Double) {
radius *= factor
}
}
// Protocol adoption in class
class Rectangle: Drawable {
var lineWidth: Double
let color: String
var width: Double
var height: Double
init(lineWidth: Double, color: String, width: Double, height: Double) {
self.lineWidth = lineWidth
self.color = color
self.width = width
self.height = height
}
func draw() {
print("Drawing rectangle \(width)x\(height)")
}
func resize(by factor: Double) {
width *= factor
height *= factor
}
}
// Using protocols as types
func render(shape: Drawable) {
print("Rendering with \(shape.color) color")
shape.draw()
}
let circle = Circle(lineWidth: 2.0, color: "red", radius: 5.0)
render(shape: circle)
// Protocol requirements for initializers
protocol Identifiable {
var id: String { get }
init(id: String)
}
struct User: Identifiable {
let id: String
let name: String
init(id: String) {
self.id = id
self.name = "Unknown"
}
}
```
Well-designed protocols are focused and cohesive, defining a single
responsibility rather than mixing unrelated requirements.
## Protocol Extensions
Protocol extensions provide default implementations to all adopting types,
enabling code reuse without inheritance and retroactive modeling of existing
types.
```swift
// Protocol with extension providing defaults
protocol Greetable {
var name: String { get }
func greet() -> String
func formalGreet() -> String
}
extension Greetable {
func greet() -> String {
return "Hello, \(name)!"
}
func formalGreet() -> String {
return "Good day, \(name)."
}
}
// Type adopts protocol, gets defaults
struct Person: Greetable {
let name: String
// greet() and formalGreet() provided by extension
}
// Type can override defaults
struct Robot: Greetable {
let name: String
func greet() -> String {
return "GREETINGS, \(name.uppercased())"
}
}
// Conditional extensions
extension Collection where Element: Equatable {
func allEqual() -> Bool {
guard let first = first else { return true }
return allSatisfy { $0 == first }
}
}
let numbers = [5, 5, 5, 5]
print(numbers.allEqual()) // true
// Extending protocols with constraints
extension Drawable where Self: AnyObject {
func drawWithRetain() {
// Only available for class types
draw()
}
}
// Adding computed properties
extension Drawable {
var description: String {
return "Shape with \(color) color and \(lineWidth)pt line"
}
}
// Protocol extension providing utilities
protocol JSONRepresentable {
func toJSON() -> [String: Any]
}
extension JSONRepresentable {
func toJSONString() -> String {
let dict = toJSON()
guard let data = try? JSONSerialization.data(
withJSONObject: dict
),
let string = String(data: data, encoding: .utf8) else {
return "{}"
}
return string
}
}
```
Protocol extensions enable retroactive modeling—adding protocol conformance to
types you don't own, including standard library types.
## Associated Types
Associated types create generic protocols, allowing conforming types to specify
concrete types that satisfy protocol requirements.
```swift
// Protocol with associated type
protocol Container {
associatedtype Item
var count: Int { get }
mutating func append(_ item: Item)
subscript(i: Int) -> Item { get }
}
// Concrete type specifies Item
struct IntStack: Container {
typealias Item = Int // explicit, but can be inferred
private var items: [Int] = []
var count: Int {
return items.count
}
mutating func append(_ item: Int) {
items.append(item)
}
subscript(i: Int) -> Int {
return items[i]
}
}
// Generic type with associated type
struct Stack<Element>: Container {
private var items: [Element] = []
var count: Int {
return items.count
}
mutating func append(_ item: Element) {
items.append(item)
}
subscript(i: Int) -> Element {
return items[i]
}
}
// Using associated types in generic functions
func printAll<C: Container>(_ container: C) where C.Item == String {
for i in 0..<container.count {
print(container[i])
}
}
// Associated type with constraints
protocol Graph {
associatedtype Node: Hashable
associatedtype Edge
func neighbors(of node: Node) -> [Node]
func edges(from node: Node) -> [Edge]
}
// Multiple associated types
protocol Transformable {
associatedtype Input
associatedtype Output
func transform(_ input: Input) -> Output
}
struct StringToIntTransformer: Transformable {
func transform(_ input: String) -> Int {
return Int(input) ?? 0
}
}
// Associated type with default
protocol Summable {
associatedtype Result = Self
func sum(with other: Self) -> Result
}
extension Int: Summable {
func sum(with other: Int) -> Int {
return self + other
}
}
```
Associated types enable protocol-based generic programming, providing
flexibility while maintaining type safety and performance.
## Protocol Composition
Protocol composition combines multiple protocols into a single requirement,
enabling precise type constraints without creating protocol hierarchies.
```swift
// Individual protocols
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
protocol Addressable {
var address: String { get }
}
// Function requiring multiple protocols
func displayInfo(for entity: Named & Aged) {
print("\(entity.name) is \(entity.age) years old")
}
struct Employee: Named, Aged, Addressable {
let name: String
let age: Int
let address: String
}
let employee = Employee(name: "Alice", age: 30, address: "123 Main St")
displayInfo(for: employee)
// Composition with classes
protocol Purchasable {
var price: Double { get }
}
func processPurchase(item: AnyObject & Purchasable) {
// Must be a class (AnyObject) and conform to Purchasable
print("Processing purchase of $\(item.price)")
}
// Protocol composition in properties
class Store {
var items: [Named & Purchasable] = []
func addItem(_ item: Named & Purchasable) {
items.append(item)
}
}
// Composition with associated types
protocol Comparable2: Equatable {
func isLessThan(_ other: Self) -> Bool
}
func sorted<T: Comparable2>(items: [T]) -> [T] {
return items.sorted { $0.isLessThan($Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.