Variable used before being initialized in function

前端 未结 6 1571
孤城傲影
孤城傲影 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:03

    Returning an Int?

    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 } 
    

    Returning Int + Fatal error

    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()
        }
    } 
    

提交回复
热议问题