20.扩展 Extensions Swift官方文档——版纳的笔
2018-03-28 本文已影响0人
KevinFromChina
//: Playground - noun: a place where people can play
import UIKit
// 注意:扩展可以加方法却不能重写方法
// # 扩展的语法
// # 计算属性
// 不能在extension中添加存储属性
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 // trick
let threeFeet = 3.ft
// # 初始化器
// 只能添加便捷初始化器,不能添加指定初始化器或反初始化器
// 为值类型添加init时能够调用原来的默认初始化器.
struct Size {
var width = 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)
}
}
let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0))
// # 方法
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
3.repetitions {
print("Hello!")
}
// 异变实例方法
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()
// # 下标
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
999000[0]
// # 内嵌类型
extension Int {
enum Kind {
case negative, zero, positive
}
var kind: Kind {
switch self {
case 0:
return .zero
case let x where x > 0:
return .positive
default:
return .negative
}
}
}
func printIntegerKinds(_ numbers: [Int]) {
for number in numbers {
switch number.kind {
case .negative:
print("- ", terminator: "")
case .zero:
print("0 ", terminator: "")
case .positive:
print("+ ", terminator: "")
}
}
print("")
}
printIntegerKinds([3, -2, 0])
(-9).kind