Swift Tutorial · Collections and Types · Lesson 17 of 30

Swift Extensions

Add methods, computed properties, initializers and protocol conformances to existing types.

Create a free account to save this page, take notes and track your progress. Sign in

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.

Extensions with properties, methods and conformances
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?

  1. Methods
  2. Computed properties
  3. Stored properties
  4. Protocol conformances
Show answer

Answer: Stored properties

Was this page helpful?