协议扩展

2021-12-28  本文已影响0人  一个栗

extension

extension 的能力

计算属性

初始化器

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")
}

执行结果如下:
hello
hello
hello

mutating 方法

extension Int {
    mutating func square() {
        self = self * self
    }
}

var someInt = 3
someInt.square()
print("\(someInt)")

执行结果如下:
9

下标

extension Int {
    subscript(digitIndex: Int) -> Int {
        var decimalBase = 1
        for _ in 0..<digitIndex {
            decimalBase *= 10
        }
        
        print("\((self / decimalBase) % 10)")
        return (self / decimalBase) % 10
    }
}
746381295[0]
746381295[1]
746381295[2]
746381295[8]

执行结果如下:
5
9
2
7

添加内嵌类型

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
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读