Swift Language What are extensions and when to use them


Example

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code.

Extensions in Swift can:

  • Add computed properties and computed type properties
  • Define instance methods and type methods
  • Provide new initializers
  • Define subscripts
  • Define and use new nested types
  • Make an existing type conform to a protocol

When to use Swift Extensions:

  • Additional functionality to Swift
  • Additional functionality to UIKit / Foundation
  • Additional functionality without messing with other persons code
  • Breakdown classes into: Data / Functionality / Delegate

When not to use:

  • Extend your own classes from another file

Simple example:

extension Bool {
    public mutating func toggle() -> Bool {
        self = !self
        return self
    }
}

var myBool: Bool = true
print(myBool.toggle()) // false

Source