Swift - Custom setter on property

后端 未结 2 1826
野性不改
野性不改 2020-12-01 18:19

I am converting a project in to Swift code and have come across an issue in a setter. My Objective-C code looked like this:

- (void)setDocument:(MyDocument *         


        
相关标签:
2条回答
  • 2020-12-01 18:25

    Here's a Swift 3 version

    var document : UIDocument? {
        didSet {
            useDocument()
        }
    }
    
    0 讨论(0)
  • 2020-12-01 18:26

    You can't use set like that because when you call self.document = newValue you're just calling the setter again; you've created an infinite loop.

    What you have to do instead is create a separate property to actually store the value in:

    private var _document: UIDocument? = nil
    var document: UIDocument? {
        get {
            return self._document
        }
        set {
            self._document = newValue
            useDocument()
        }
    }
    
    0 讨论(0)
提交回复
热议问题