Home > database >  switch and cannot find variable in scope
switch and cannot find variable in scope

Time:11-28

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

CodePudding user response:

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.

  • Related