vendredi 31 juillet 2020

Swift: switch vs if-else statement to examine a random integer

I'm about to learn the Swift programming language. I just wrote a function that generates a random integer in a range of 0...2. Afterwards the function returns an enum type conditionally.

I'd like to prefer to use the case statement but I don't like the default case which returns an arbitrary enum. Omitting the default case not work since switch is not able to know how much cases will occur. Even though the default case would never happen I don't consider this to be a clean solution.

Which solution would you prefer respectively consider to be the cleanest solution - please elaborate.

If-else solution:

    func generateRandomSign() -> Sign {
        let randomSelection = Int.random(in: 0...2)

        if randomSelection == 0 {
            return .rock
        } else if randomSelection == 1 {
            return .paper
        } else if randomSelection == 2 {
            return .scissor
        }
    }

Switch solution:

    func generateRandomSign() -> Sign {
        let randomSelection = Int.random(in: 0...2)

        switch randomSelection {
        case 0: return .rock
        case 1: return .paper
        case 2: return .scissor
        default: return .rock
        }
    }

Best regards

Aucun commentaire:

Enregistrer un commentaire