在扩展中的弱 属性 上添加 didSet 观察者

Add didSet observer on a weak property in an extension

我正在尝试制作一个 UITextField 扩展,它根据委托的设置执行附加功能。

extension UITextField {
    override weak public var delegate: UITextFieldDelegate? {
        didSet {
            print("Do stuff")

        }  
    }
}

失败并出现三个错误:

'delegate' used within its own type

'weak' cannot be applied to non-class type '<<error type>>'

Property does not override any property from its superclass

我需要更改什么才能 Do stuff 在代理设置时打印?

您不能使用扩展覆盖委托 属性,您需要创建子类:

class TextField: UITextField {
    override weak var delegate: UITextFieldDelegate? {
        didSet {
            super.delegate = delegate
            print("Do stuff")
        }
    }
}

但这似乎有点不对。你想达到什么目的?