Swift扩展(Extension)
Posted slgkaifa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swift扩展(Extension)相关的知识,希望对你有一定的参考价值。
在现有类和结构体的类型基础上,扩展新的功能。
语法:
extension SomeType{ // new functionality to add to SomeType goes here } An extension can extend an existing type to make itadopt one or more protocols.Where this is the case, the protocol names are written in exactly the sameway as for a class or structure: extension SomeType: SomeProtocol,AnotherProtocol { // implementation of protocol requirements goes here }
计算属性
extension Double{ var km: Double { return self * 1_000.0 } var m: Double { return self } var cm: Double { return self / 100.0} var mm: Double { return self /1_000.0 } var ft: Double { return self / 3.28084 } } let oneInch = 25.4.mm println("One inch is \(oneInch) meters") // prints "One inch is 0.0254 meters" let threeFeet =3.ft println("Three feet is \(threeFeet) meters") // prints "Three feet is0.914399970739201 meters" let aMarathon = 42.km + 195.m println("Amarathon is \(aMarathon) meters long")
使用构造器
struct Size { varwidth = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size= Size() } extension Rect{ init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height/ 2) self.init(origin: Point(x: originX, y: originY), size: size)//调用 Rect 结构体构造器} } let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0))
方法扩展
struct Size { varwidth = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size= Size() } extension Rect{ init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height/ 2) self.init(origin: Point(x: originX, y: originY), size: size)//调用 Rect 结构体构造器 } } let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0))
Swift交流讨论论坛论坛:http://www.cocoagame.net
欢迎增加Swift技术交流群:362298485
以上是关于Swift扩展(Extension)的主要内容,如果未能解决你的问题,请参考以下文章
在 Swift 中,从 App Extension 目标运行时如何忽略部分代码?
Swift - 协议类扩展(extension) 访问控制(fileprivate,private,internal,public,open)