Swift 关键字 -- Extension

官方对于 extension 使用的解释Swift Extensions doc

1. 与 OC 分类相似,但是没有名字区别

Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions don’t have names.)

2. 使用的几个场景

Extensions in Swift can:

  • Add computed instance properties and computed type properties
  • Define instance methods and type methods
  • Provide new initializers
  • Define subscripts
  • Define and use new nested types
  • Make an existing type conform to a protocol

2.1 添加计算属性

tips

Extensions can add new computed properties, but they can’t add stored properties, or add property observers to existing properties.
允许添加计算属性,不允许添加存储属性,或者添加已声明属性的观察服务。

/// 添加计算属性
extension Double {
    var m: Double {
        return self
    }
    var km: Double {
        return self / 1000
    }
    var cm: Double {
        return self * 1000
    }
}

let result = 50 * 1.0.cm + 10.m // 10.5.m

2.2 定义对象方法/常量方法

/// 添加方法

class ExtensionDemo {
    
}

/// 对象添加方法
extension ExtensionDemo {
    /// 添加静态方法
    static func staticMethod() -> Void {
        
    }
    /// 添加实例方法
    func instanceMethod() -> Void {
        
    }
}

/// 常量添加方法
extension Int {
    func repetitions(task: () -> Void) {
        for _ in 0.. Int {
        self = x * y
        return self
    }
}

func methodDemo() -> Void {
    ExtensionDemo.staticMethod()
    ExtensionDemo().instanceMethod()
    10.repetitions {
        print("1")
    }
}

2.3支持添加新的构造方法

/// 添加构造方法

extension Int {
    init(x: Double, y: Double) {
        self.init(x * y)
    }
}

2.4 支持 Subscripts

/// 支持 Subscripts

extension Int {
    subscript(index: Int) -> Int {
        return 0
    }
}

let index = 100[0]

2.5 Define and use new nested types

Extensions can add new nested types to existing classes, structures, and enumerations:

classes,
structures,
enumerations:

/// 支持嵌套类型

enum ExtensionEnumDemo {
    case first
    case second
}

/// 枚举支持内嵌对象

extension ExtensionEnumDemo {
    class ExtensionSub {
        
    }
}

/// 对象支持内嵌对象

extension ExtensionDemo {
    
    class ExtensionSub {
        
    }
}

/// 结构体支持内嵌对象

extension Int {
    
    class ExtensionSub {
        
    }
    
    enum Types {
        case first
        case second
    }
}

2.6 Make an existing type conform to a protocol 已有类型支持协议

/// 支持协议


extension UIViewController : UITableViewDelegate {
    
    func cellForRow(at indexPath: IndexPath) -> UITableViewCell? {
        return nil
    }
    
}

谢谢大家,有问题请留言.

你可能感兴趣的:(Swift 关键字 -- Extension)