Every possible path in the flow of a Swift program must have a defined returned value. In your case, if the if
/else if
/else
sections are all skipped, leaving returnval
unassigned. Thus, no valid value is being returned. Try this:
import Foundation
import UIKit //space things out to be easier to read
class Result: UIViewController {
var rval: Int? //these should have better names
var chosen: Int?
func determineWinner() -> Int {
var returnval = -1 //needs a default value
if (chosen == rval){
returnval = 2
}
else if (chosen == 1 && rval == 3){
returnval = 1
}
else if (chosen == 1 && rval == 2){
returnval = 0
}
else if (chosen == 2 && rval == 1){
returnval = 1
}
return returnval //don't put return value in brackets
}
@IBOutlet weak var wl: UILabel!
@IBAction func PlayAgain(sender: AnyObject) {
}
override func viewDidLoad() {
print(chosen)
}
}
This is also a very good candidate for using pattern matching with switch
statements. Here's what I think works beside, in conjunction withSean's suggestion.
var determineWinner: Int? {
guard let chosen = chosen, let rval = rval else {
//handle error, either chosen or rval is nil
return nil
}
switch ((chosen, rval)) {
case let (x, y) where x == y: return 2
case (1, 3): return 1
case (1, 2): return 0
case (2, 1): return 1
default:
print("handle default case here")
return nil;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…