How to assign a variable in a Swift case statement

Put the switch in an anonymous closure, if you'll only use that code in one place.

string1 = {
    switch var1 {
    case 1:
        return "hello"
    case 2:
        return "there"
    default:
        return "hello"
    }
}()

You could put your switch block in a function that returns a String object, and assign the return of this function to your variable string1:

func foo(var1: Int) -> String {
    switch var1 {
    case 1:
        return "hello"
    case 2:
        return "there"
    default:
        return "world"
    }
}

/* Example */
var var1 : Int = 1
var string1 : String = foo(var1) // "hello"
var1 = 2
string1 = foo(var1)              // "there"
var1 = 5000
string1 = foo(var1)              // "world"

Alternatively let string1 be a computed property (e.g. in some class), depending in the value of say var1, and place the switch block in the getter of this property. In a playground:

var var1 : Int
var string1 : String {
    switch var1 {
    case 1:
        return "hello"
    case 2:
        return "there"
    default:
        return "world"
    }
}

/* Example */
var1 = 1
print(string1) // hello
var1 = 2
print(string1) // there
var1 = 100
print(string1) // world

If used in a class, just skip the Example block above.

Tags:

Swift