Swift 关联对象

Swift Extension 能够给已有类添加计算型属性,但是仍然不能添加存储属性。Swift 中也可以使用 Objective-C runtime 的关联对象(Associated Objects)的方式添加属性,弥补这一痛点。

extension UIView { // 嵌套结构体 private struct AssociatedKeys { static var displayNameKey = "displayNameKey" } // String 类型 var displayName: String? { get { return objc_getAssociatedObject(self, &AssociatedKeys.displayNameKey) as? String } set { objc_setAssociatedObject(self, &AssociatedKeys.displayNameKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } } } // 关联闭包属性 typealias pushCompletionClosure = ()->() extension UIViewController { private struct AssociatedKeys { static var pushCompletionKey = "pushCompletionKey" } var pushCompletion: pushCompletionClosure? { get { return objc_getAssociatedObject(self, &AssociatedKeys.pushCompletionKey) as? pushCompletionClosure } set { objc_setAssociatedObject(self, &AssociatedKeys.pushCompletionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } } }