Swift Functional Programming(Second Edition)
上QQ阅读APP看书,第一时间看更新

Extensions

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

Extensions in Swift enables us to perform the following:

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

Extensions enable us to add new functionality to a type, but we will not be able to override the existing functionality.

In the following example, we extend AType by making it conform to two protocols:

extension AType: AProtocol, BProtocol { } 

The following example presents an extension to Double by adding computed properties:

extension Double { 
var mm: Double{ returnself / 1_000.0 }
var ft: Double{ returnself / 3.2884 }
}

let threeInch = 76.2.mm
let fiveFeet = 5.ft