Override a setter in swift

2020-02-07 05:34发布

问题:

I've got a strange problem with setter in swift. I've got class PlayingCard with code:

var rank: NSInteger {
    get{
        return self.rank
    }
    set(rank){
        self.rank = rank
    }
}

var suit: NSString {
    get{
        return self.suit
    }
    set(suit){
        self.suit = suit
    }
}

init(suit: NSString, rank: NSInteger) {
    super.init()
    self.suit = suit
    self.rank = rank
}

I use this init() method in another class, and implementation looks like this:

init() {
    super.init(cards: [])
    for suit in PlayingCrad.validSuit() {
        var rank: Int = 0
        for rank; rank <= PlayingCrad.maxRank(); rank++ {
            var card = PlayingCrad(suit: suit, rank: rank)
            addCard(card)
        }
    }
}

And when the code looks like above I've got a error in line:

self.suit = suit

EXC_BAD_ACCESS(code=2, adress=0x7fff5c4fbff8)

But when I removed setter and getter from rank and suit attribute it's worked fine, no error has shown up.

Can you explain me why this EXC_BAD_ACCESS error has shown up?

Thank you for your help

回答1:

By writing this...

set(suit) {
    self.suit = suit
}

... you introduce an infinite loop, because you call the setter from within the setter.

If your property isn't computed, you should take advantage of willSet and didSet notifiers to perform any additional work before/after the property changes.

By the way, you should remove te getter as well. It will cause another infinite loop when accessing the property.



标签: swift ios8