有没有办法在 Swift 中设置关联对象? [英] Is there a way to set associated objects in Swift?

查看:27
本文介绍了有没有办法在 Swift 中设置关联对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Objective-C,你可以在 2 个对象之间调用函数 objc_setAssociatedObject 来让它们维护一个引用,如果在运行时你不希望一个对象在引用之前被销毁,这会很方便也被删除.Swift 有没有类似的东西?

Coming from Objective-C you can call function objc_setAssociatedObject between 2 objects to have them maintain a reference, which can be handy if at runtime you don't want an object to be destroyed until its reference is removed also. Does Swift have anything similar to this?

推荐答案

这是一个简单但完整的示例,源自 jckarter 的回答.

Here is a simple but complete example derived from jckarter's answer.

它展示了如何向现有类添加新属性.它通过在扩展块中定义计算属性来实现.计算属性存储为关联对象:

It shows how to add a new property to an existing class. It does it by defining a computed property in an extension block. The computed property is stored as an associated object:

import ObjectiveC

// Declare a global var to produce a unique address as the assoc object handle
private var AssociatedObjectHandle: UInt8 = 0

extension MyClass {
    var stringProperty:String {
        get {
            return objc_getAssociatedObject(self, &AssociatedObjectHandle) as! String
        }
        set {
            objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

如果您需要支持获取未初始化属性的值并避免出现unexpectedly found nil while unwrapping an Optional value,您可以像这样修改getter:

If you need to support getting the value of an uninitialized property and to avoid getting the error unexpectedly found nil while unwrapping an Optional value, you can modify the getter like this:

    get {
        return objc_getAssociatedObject(self, &AssociatedObjectHandle) as? String ?? ""
    }

这篇关于有没有办法在 Swift 中设置关联对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆