首页 > 代码库 > Swift扩展(Extension)
Swift扩展(Extension)
在现有类和结构体的类型基础上,扩展新的功能。 语法:
[html] view plaincopy
- 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
- }
计算属性
[html] view plaincopy
- 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")
使用构造器
[html] view plaincopy
- 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))
方法扩展
[html] view plaincopy
- 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。