Extensions and protocol conformance

You can also adopt protocols using extensions. This lets you add protocol conformances to types you don’t necessarily own. Consider the simple example below which adds a custom protocol to String:

protocol Reflective {

var typeName: String { get }

}

extension String: Reflective { var typeName: String {

return "I'm a String"

}

}

let title = "Swift Apprentice!" title.typeName // I'm a String

Even though String is part of the standard library and not accessible to your code, you’re still able to make String adopt and conform to the Reflective protocol. The other advantage is you can nicely group together the protocol adoption with the requisite methods and properties, instead of having a pile of protocols cluttering up your type definition.

The following code breaks out the adoption of Wheeled and Vehicle into extensions on Bike:

class AnotherBike { var peddling = false var wheelSize = 16.0

}

extension AnotherBike: Wheeled { var numberOfWheels: Int {

return 2

}

// wheelSize already implemented in main body.

}

extension AnotherBike: Vehicle { func accelerate() {

peddling = true

}

func stop() { peddling = false

}

}

The extensions now pair numberOfWheels with Wheeled, and also pairs accelerate and stop with Vehicle. If you were to remove a protocol from Bike, you could simply delete the extension that adopts that protocol entirely.

A caveat: you can’t declare stored properties like wheelSize in extensions, just computed properties such as numberOfWheels. You can still declare stored properties in the original type declaration and satisfy protocol conformance to any protocol adopted in an extension, but completely implementing protocols in extensions isn’t always possible due to the limits of extensions.

results matching ""

    No results matching ""