2

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

LakaLe_
  • 454
  • 1
  • 6
  • 15
  • 1
    My question is "why are you providing custom implementations of get and set that attempt to do nothing more than the default would?" If you're trying to do some additional handling when those properties are set then willSet/didSet would be a much better approach. – David Berry Aug 17 '14 at 17:18

1 Answers1

4

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.

akashivskyy
  • 44,342
  • 16
  • 106
  • 116