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

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
主站蜘蛛池模板: 谢通门县| 滦南县| 鄢陵县| 犍为县| 鲁山县| 濮阳县| 德化县| 阜阳市| 宁蒗| 唐海县| 崇左市| 樟树市| 同仁县| 遂平县| 嘉兴市| 钟祥市| 铜陵市| 马公市| 临桂县| 衡山县| 巢湖市| 北流市| 寿阳县| 汤原县| 百色市| 惠东县| 阿勒泰市| 鱼台县| 敦煌市| 绥滨县| 鹤岗市| 集安市| 玉山县| 招远市| 麻江县| 达尔| 横山县| 苏尼特左旗| 上思县| 梁平县| 新邵县|