Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. protocol Basics / Conformance

protocol Basics / Conformance

In Swift, a protocol defines a blueprint of methods and properties that a type must implement. Structs, classes, and enums can all conform to protocols.

Syntax

// Define a protocol
protocol ProtocolName {
    // Required property (read-only or read-write)
    var readOnly: Type { get }
    var readWrite: Type { get set }

    // Required method
    func methodName() -> Type

    // Mutating method (for struct conformance)
    mutating func mutatingMethod()
}

// Conform to a protocol
struct TypeName: ProtocolName {
    // Implement all protocol requirements
}

Syntax List

SyntaxDescription
protocol Name { }Defines a protocol.
var prop: T { get }Declares a read-only property requirement.
var prop: T { get set }Declares a read-write property requirement.
func method()Declares a required method.
struct Type: Protocol { }Defines a type that conforms to a protocol.
Protocol composition with &Represents a type that conforms to multiple protocols (protocol1 & protocol2).

Sample Code

// Define protocols
protocol Describable {
    var description: String { get }
    func describe()
}

protocol Resizable {
    mutating func resize(by factor: Double)
    var area: Double { get }
}

// Conform a struct to both protocols
struct Circle: Describable, Resizable {
    var radius: Double

    var description: String {
        return "Circle (radius: \(radius))"
    }

    func describe() {
        print(description)
    }

    var area: Double {
        return Double.pi * radius * radius
    }

    mutating func resize(by factor: Double) {
        radius *= factor
    }
}

var circle = Circle(radius: 5.0)
circle.describe()
print("Area: \(String(format: "%.2f", circle.area))")

circle.resize(by: 2.0)
circle.describe()

// Use a protocol as a type
func printInfo(_ item: Describable) {
    item.describe()
}

printInfo(circle)

// Protocol composition (& operator)
func resizeAndDescribe(_ item: inout Describable & Resizable, by factor: Double) {
    item.resize(by: factor)
    item.describe()
}

Overview

A protocol defines "what a type can do." By conforming different types to the same protocol, you can achieve polymorphism.

Even if a property requirement is declared as { get } in a protocol, the conforming type can implement it as either a stored property or a computed property. The mutating keyword is required when a struct or enum conforms to a protocol that declares mutating methods. When a class conforms, you can omit mutating.

For protocol default implementations, see Protocol Default Implementations / Protocol Composition.

If you find any errors or copyright issues, please .