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!
Declaring a variable inside a switch block is fine. Declaring after a case guard is not.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With