码迷,mamicode.com
首页 > 编程语言 > 详细

Swift扩展(Extension)

时间:2017-06-25 12:43:50      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:toc   line   struct   existing   font   exist   构造   pac   erp   

在现有类和结构体的类型基础上,扩展新的功能。

语法:

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)

标签:toc   line   struct   existing   font   exist   构造   pac   erp   

原文地址:http://www.cnblogs.com/slgkaifa/p/7076464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!