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

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
主站蜘蛛池模板: 许昌县| 麻栗坡县| 大城县| 那坡县| 武定县| 普洱| 思南县| 昂仁县| 荥经县| 获嘉县| 林西县| 林口县| 右玉县| 紫云| 东乌| 吴忠市| 郧西县| 大名县| 禹州市| 旬邑县| 桐庐县| 泸定县| 墨竹工卡县| 普格县| 平山县| 天峨县| 庆城县| 化德县| 新化县| 南靖县| 永寿县| 宝兴县| 府谷县| 西安市| 镇巴县| 志丹县| 永昌县| 五家渠市| 林口县| 宝山区| 明光市|