在现有类和结构体的类型基础上,扩展新的功能。 语法:
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),布布扣,bubuko.com
原文地址:http://blog.csdn.net/tonny_guan/article/details/36198911