Swift 扩展

2020-02-20  本文已影响0人  Arthur澪

为现有的类、结构体、枚举类型、或协议添加了新功能。与 OC 中的Category类似,不同的是,Swift 的扩展没有名字。

Swift 中的扩展的作用:
1、添加计算实例属性、计算类型属性;
2、定义实例方法、类方法;
3、提供新初始化器;
4、定义下标;
5、定义和使用新内嵌类型;
6、使现有的类型遵循某协议
7、扩展现有的协议

关键字extension

extension SomeType {
    // new functionality to add to SomeType goes here

}
// 使已有的类型遵循一个或多个协议 
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
print("One inch is \(oneInch) meters")
// Prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// Prints "Three feet is 0.914399970739201 meters"
Int类型添加方法repetitions
extension Int {
    func repetitions(task: () -> Void) {
        for _ in 0..<self {
            task()
        }
    }
}

3.repetitions {
    print("Hello!")
}
extension Int {
    subscript(digitIndex: Int) -> Int {
        var decimalBase = 1
        for _ in 0..<digitIndex {
            decimalBase *= 10
        }
        return (self / decimalBase) % 10
    }
}
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
        }
    }
}
protocol TestProtocol {
    func test()
}
class TestClass {
    func test() {
        print("test")
    }
}

extension TestClass : TestProtocol {

}
protocol TestProtocol {
    func test1()
}
extension TestProtocol {
    func test1() { 
        print("TestProtocol test1")
    }
    func test2() {
        print("TestProtocol test2") 
    }
}

class TestClass : TestProtocol {

} 

var cls = TestClass()
cls.test1() // TestProtocol test1 
cls.test2() // TestProtocol test2 
var cls2: TestProtocol = TestClass() 
cls2.test1() // TestProtocol test1 
cls2.test2() // TestProtocol test2
上一篇下一篇

猜你喜欢

热点阅读