I\'m making a ro sham bo game. Functions in swift are different than what I have used before. I keep getting an error:
Variable used before being init
As others already said, the problem is that none of your conditions is met then returnval
is not initialized.
You can use a switch statement + guard + computed property. Like this
var winner: Int? {
guard let chosen = chosen, rval = rval else { return nil }
switch (chosen, rval) {
case (let chosen, let rval) where chosen == rval : return 2
case (1, 3): return 1
case (1, 2): return 0
case (2, 1): return 1
default: return nil
}
}
Please note I slightly changed your logic. Infact in my code if chosen and rval are both nil the returned value is nil. While in your code 2 is returned. You should change it, maybe adding another
guard
on top of my code. Something like
guard chosen != rval else { return 2 }
If you know chose and rval will always be populated then
var winner: Int {
guard let chosen = chosen, rval = rval else { fatalError() }
switch (chosen, rval) {
case (let chosen, let rval) where chosen == rval : return 2
case (1, 3): return 1
case (1, 2): return 0
case (2, 1): return 1
default: fatalError()
}
}