Use "return" ore not?

Hello guys,

I'm new to programming and have just startet to my make first app.

In my code i have over 40 ''if' statments after each other, and was wondring if i should end each statement with ''return''.

After looking around online and reading some mixed answers, I was was hoping some of you could tell me if you would have used "return"? and why?


Eks:

if ranNumber == 1 { label.text = "text"; score += 1 }

else if ranNumber == 2 { label.text = "text"; score += 1 }

else if ranNumber == 3 { label.text = "text"; score += 1 }

.......

Ore should i throw away all the ''if'' statements, and take a diffrent approach to make it shorter? Any suggestions? (except from the switch statement)

Replies

edit:

if ranNumber == 1 { label.text = "text"; scoreA += 1 }

else if ranNumber == 2 { label.text = "text"; scoreB += 1 }

else if ranNumber == 3 { label.text = "text"; scoreC += 1 }

it would be better to use a switch statement:


switch ranNumber {

case 1 : labelText = "text1"

scoreA += 1

case 2: labelText = "text2"

scoreB += 1

default : labelText = "error"

}

The answer to whether a return is needed in each if statement depends on the entire code in your function/method and what you actually intend to happen in the function/method.


Anyway, consider using an array of scores instead of an individual variable for each score. A simplistic example:


let numberOfScores = 40
var scores = Array(repeating: 0, count: numberOfScores)

func updateScores(usingNumber number: Int) {
  // Assuming number will be in range 1...numberOfScores.
  // An array's indices are zero-based, so subtract 1 from number to form the corresponding index.
  let index = number - 1
  scores[index] += 1
}

func updateLabel(usingNumber number: Int) {
  // Some code.
}

let number = 3 // an Int in range 1...numberOfScores
updateScores(usingNumber: number)
updateLabel(usingNumber: number)

I generally try to avoid conditionals in situations like this. What is the scope of

ranNumber
? For example:
  • If

    ranNumber
    has a relatively limited set of values, I might use an
    enum
    for
    ranNumber
    and then have the text and score increments be properties of that enum
  • If

    ranNumber
    has a lot of related values, I might derive the text and scores algorithmically from it
  • If

    ranNumber
    has lots of unrelated values, I might use a table to map
    ranNumber
    to the text and score

If you can expand your description of the problem we should be able to offer you more concrete advice.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"