BudiBadu Logo
Samplebadu

Swift by Example: Protocols

Swift 5.x

Understanding Swift protocols with this code example demonstrating protocol definitions as blueprints, property requirements with get/set specifications, protocol adoption by structs and classes, conformance through implementation, and computed properties satisfying protocol requirements.

Code

protocol FullyNamed {
    var fullName: String { get }
}

struct Person: FullyNamed {
    var fullName: String
}

class Starship: FullyNamed {
    var prefix: String?
    var name: String
    
    init(name: String, prefix: String? = nil) {
        self.name = name
        self.prefix = prefix
    }
    
    // Conforming to the protocol (computed property)
    var fullName: String {
        return (prefix != nil ? prefix! + " " : "") + name
    }
}

let nc = Starship(name: "Enterprise", prefix: "USS")
print(nc.fullName) // "USS Enterprise"

Explanation

Protocols define a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. This is similar to interfaces in Java or C#.

A protocol can require that conforming types provide an instance property with a specific name and type. It also specifies whether the property must be gettable or gettable and settable. In the example, FullyNamed requires a read-only fullName property.

Swift uses protocols heavily (Protocol-Oriented Programming). You can use protocols as types in your code, allowing for polymorphism. For example, you can have an array of [FullyNamed] objects containing both Person structs and Starship classes, and access their fullName property safely.

Code Breakdown

1
protocol FullyNamed defines a blueprint for types to conform to.
2
var fullName: String { get } requires a gettable string property.
5
struct Person: FullyNamed adopts the protocol with a colon.
17-19
var fullName: String { ... } implements the protocol requirement as a computed property.