Resolve recursion in Swift property override

后端 未结 1 1639
挽巷
挽巷 2021-01-21 13:36

Here\'s a simple extension in Swift, for UILabel,

let dur=0.1 // (set to say 2.0 to see the effect more clearly)
extension UILabel
    {
    func change(s:String         


        
1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-21 14:03

    Your recursion is called when you use self.text= to assign a new value in your change extension method because this will call the setter, which calls change and so on.

    In your second example, you avoid recursion because you can call the superclass setter from your subclass setter. You don't have this option in your extension because your code is running as an extension to UILabel and therefore there is no superclass setter to call.

    Arguably creating a subclass rather than using extension is the more correct approach in this instance anyway

    0 讨论(0)
提交回复
热议问题