Variable used before being initialized in function

前端 未结 6 1584
孤城傲影
孤城傲影 2020-12-12 06:14

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

6条回答
  •  心在旅途
    2020-12-12 07:01

    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;
        }
    }
    

提交回复
热议问题