Extensions - RaduG/swift_learning GitHub Wiki

Overview

Extensions in Swift can:

  • Add computed instance 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

Extensions affect all future and existing instances of the extended type.

Syntax:

extension SomeType {
  // extends functionality of SomeType
}

extension SomeType: Protocol1, Protocol2 {
  // extends SomeType with protocol conformance
}

Example

extension Int {
  var squared: Int {
    self * self
  }
}

print(10.squared)