Override a setter in swift

纵饮孤独 提交于 2019-12-17 20:56:08

问题


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.



来源:https://stackoverflow.com/questions/25348049/override-a-setter-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!