Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a variable in a Swift case statement

Tags:

swift

This works but seems inefficient:

switch var1 {
case 1:
    string1 = "hello"
case 2:
    string1 = "there"
default:
    string1 = "world"
}

but

string1 = switch var1 { ...

throws an error. Is there a more efficient way to write the switch/case so that the assigned variable isn't listed redundantly in each line?

Thanks in advance!

like image 687
Dribbler Avatar asked Jan 14 '16 22:01

Dribbler


People also ask

Can we declare a variable in switch case?

Declaring a variable inside a switch block is fine. Declaring after a case guard is not.

Do we need break in switch case Swift?

Although break isn't required in Swift, you can use a break statement to match and ignore a particular case or to break out of a matched case before that case has completed its execution. For details, see Break in a Switch Statement. The body of each case must contain at least one executable statement.

What is switch case in Swift?

A switch statement in Swift completes its execution as soon as the first matching case is completed instead of falling through the bottom of subsequent cases like it happens in C and C++ programing languages.


2 Answers

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"     } }() 
like image 142
Tom Harrington Avatar answered Oct 22 '22 04:10

Tom Harrington


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.

like image 42
dfrib Avatar answered Oct 22 '22 04:10

dfrib