Is there a way to do conditional assignment to constants in Swift?

You could also do this

var someConstant: String {
    if #available(iOS 9, *) {
        return "iOS 9"
    } else {
        return "not iOS 9"
    }
}

By doing this you can't assign a value to the variable someConstant even if it is a var and not a let because it is a calculated property

Another way of doing this would be to use free functions.

let someConstant: String = {
    if #available(iOS 9, *) {
        return "iOS 9"
    } else {
        return "not iOS 9"
    }
}()

The difference between the first example from the second example is that the second example is only instantiated once.


Do the declaration and assignment on two separate lines:

let attribs: [NSAttributedString.Key: Any]
if #available(iOS 8.2, *) {
    attribs = [.font: UIFont.systemFont(ofSize: 30, weight: .light)]
} else {
    attribs = [.font: UIFont.systemFont(ofSize: 30)]
}

Even though it is a let, you can do the assignment (only once per path of execution) on a separate line.


I think you want something like this:

let value: String
if #available(iOS 9, *) {
    value = "iOS 9 is available"
} else {
    value = "iOS 9 and up only"
}
print(value) // iOS 9 is available