Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I create a constant that could be one of several strings depending on conditions?

Tags:

swift

I want to have a constant using let that may be one of several values.

For instance:

if condition1 {
   constant = "hi"
}
else if condition2 {
   constant = "hello"
}
else if condition3 {
   constant = "hey"
}
else if condition4 {
   constant = "greetings"
}

I'm not sure how to do this with Swift and the let feature. But I'm inclined to believe it's possible, as this is in the Swift book:

Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.

How would I accomplish this?

like image 901
Doug Smith Avatar asked Jun 10 '14 04:06

Doug Smith


2 Answers

As pointed out in the other answers you can't directly do this. But if you're looking to just variably set the initial value of a constant, then yes, that is possible. Here's an example with a computed property.

class MyClass {
    let aConstant: String = {
        if something == true {
            return "something"
        } else {
            return "something else"
        }
    }()
}
like image 170
Mick MacCallum Avatar answered Nov 07 '22 10:11

Mick MacCallum


I think you are looking for variable which will be assigned later inside switch-case:

let constant :String

switch conditions {
case condition1:
    constant = "hi"
case condition2:
    constant = "hello"
case condition3:
    constant = "hey"
case condition4:
    constant = "greetings"
default:
    constant = "salute"
}
like image 4
vondra Avatar answered Nov 07 '22 09:11

vondra