Swift Tutorial · Collections and Types · Lesson 17 of 30
Swift Extensions
Add methods, computed properties, initializers and protocol conformances to existing types.
Extending existing types
An extension adds functionality to any type, including String, Int and types from frameworks you don't
own. Extensions can add methods, computed properties, initializers, nested types and protocol conformances,
but not stored properties.
import Foundation
extension String {
var slug: String {
lowercased()
.split(whereSeparator: { !$0.isLetter && !$0.isNumber })
.joined(separator: "-")
}
}
extension Int {
var isEven: Bool { self % 2 == 0 }
func times(_ action: () -> Void) { for _ in 0..<self { action() } }
}
struct Money { let cents: Int }
extension Money: CustomStringConvertible {
var description: String { "EUR \(cents / 100).\(String(format: "%02d", cents % 100))" }
}
print("Swift Concurrency: A Guide!".slug)
print((1...6).filter(\.isEven))
3.times { print("hi", terminator: " ") }
print()
print(Money(cents: 1999))
Output
swift-concurrency-a-guide [2, 4, 6] hi hi hi EUR 19.99
Run this on your computer — see “Get Started” for setup.
Test yourself
What can't an extension add to a type?
MethodsComputed propertiesStored propertiesProtocol conformances
Show answer
Answer: Stored properties