官术网_书友最值得收藏!

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
主站蜘蛛池模板: 保康县| 章丘市| 江津市| 股票| 玉门市| 凤凰县| 洮南市| 六盘水市| 晋中市| 嘉禾县| 册亨县| 大埔区| 宁津县| 岗巴县| 会东县| 平舆县| 仁布县| 万宁市| 平远县| 蒙阴县| 平陆县| 五寨县| 庆城县| 开远市| 綦江县| 永丰县| 高邑县| 工布江达县| 甘孜| 育儿| 淳化县| 耒阳市| 惠安县| 木里| 嘉禾县| 屏东市| 宜章县| 城市| 金华市| 靖远县| 砀山县|