0

Why should I create a variable outside of switch/case? For example this code will have an error Cannot find 'size' in scope:

func sizeCheckNoVar(value: Int) -> String {
        switch value {
        case 0...2:
            let size = "small"
        case 3...5:
            let size = "medium"
        case 6...10:
            let size = "large"
        default:
            let size = "huge"
            
        }
        return size
    }

There is a default condition and AFIK all options are covered.

In the same time this code will be fine:

func sizeCheckVar(value: Int) -> String {
    var size: String
    switch value {
    case 0...2:
        size = "small"
    case 3...5:
        size = "medium"
    case 6...10:
        size = "large"
    default:
        size = "huge"
        
    }
    return size
}

PS I saw this question Cannot find variable in scope , but I want to know why instead of how to avoid

2
  • 1
    Because when you create a variable inside the case then the scope of the variable is within the case and you can’t access the variables outside the case Commented Nov 27, 2021 at 8:51
  • For the easy way returns the value direct from the case like case 0..2: return “small” … no need any variables Commented Nov 27, 2021 at 8:53

1 Answer 1

3

A pair of braces is called a scope.

In Swift (unlike some other languages) there is a simple but iron rule:

  • A variable declared inside a scope – in your particular case inside the switch statement – is visible in its own scope and on a lower level – like in your second example

  • It's not visible on a higher level outside the scope – like in your first example.

You can even declare size as constant because it's guaranteed to be initialized.

func sizeCheckVar(value: Int) -> String {
    let size: String
    switch value {
      case 0...2: size = "small"
      case 3...5: size = "medium"
      case 6...10: size = "large"
      default: size = "huge"
    }
    return size
}

However actually you don't need the local variable at all. Just return the values immediately

func sizeCheckVar(value: Int) -> String {
    switch value {
      case 0...2: return "small"
      case 3...5: return "medium"
      case 6...10: return "large"
      default: return "huge"
    }
}

Side note: The colon in a switch statement is also a kind of scope separator otherwise you would get errors about redeclaration of variables in the first example.

Sign up to request clarification or add additional context in comments.

2 Comments

How can I put the return value into a variable?
@submariner let myVariable = sizeCheckVar(value: 4)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.