< When should you use extensions in Swift? | How is protocol-oriented programming different from object-oriented programming? > |
Updated for Xcode 14.2
Protocol extensions are used everywhere in Swift, which is why you’ll often see it described as a “protocol-oriented programming language.” We use them to add functionality directly to protocols, which means we don’t need to copy that functionality across many structs and classes.
For example, Swift’s arrays have an allSatisfy()
method that returns true if all the items in the array pass a test. So, we could create an array of numbers and check that they are all even:
let numbers = [4, 8, 15, 16]
let allEven = numbers.allSatisfy { $0.isMultiple(of: 2) }
That’s really useful, but wouldn’t it be more useful if it also worked on sets? Sure it would, and that’s why it does:
let numbers2 = Set([4, 8, 15, 16])
let allEven2 = numbers2.allSatisfy { $0.isMultiple(of: 2) }
The underlying principle is identical: pass each item in the array or set through a test you provide, and if that returns true for all items then the result of the method is true.
How about dictionaries – can they use this too? Sure they can, and it works identically: each key/value pair gets passed into the closure, and you need to return either true or false. It looks like this:
let numbers3 = ["four": 4, "eight": 8, "fifteen": 15, "sixteen": 16]
let allEven3 = numbers3.allSatisfy { $0.value.isMultiple(of: 2) }
Of course, the Swift developers don’t want to write this same code again and again, so they used a protocol extension: they wrote a single allSatisfy()
method that works on a protocol called Sequence
, which all arrays, sets, and dictionaries conform to. This meant the allSatisfy()
method immediately became available on all those types, sharing exactly the same code.
SPONSORED Build a functional Twitter clone using APIs and SwiftUI with Stream's 7-part tutorial series. In just four days, learn how to create your own Twitter using Stream Chat, Algolia, 100ms, Mux, and RevenueCat.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.