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

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
主站蜘蛛池模板: 遵义市| 武隆县| 武邑县| 卓尼县| 郧西县| 曲麻莱县| 新乡市| 贵港市| 九龙县| 福贡县| 佛山市| 全椒县| 成安县| 石泉县| 建平县| 昂仁县| 淮滨县| 丹寨县| 祁门县| 临湘市| 伊春市| 浦北县| 昆明市| 海原县| 灌南县| 永康市| 淮北市| 通江县| 黔西| 新泰市| 隆林| 九龙城区| 靖远县| 江华| 滨州市| 瑞安市| 千阳县| 浠水县| 衡南县| 龙里县| 四子王旗|