C. Keith Ray

C. Keith Ray writes about and develops software in multiple platforms and languages, including iOS® and Macintosh®.
Keith's Résumé (pdf)

Saturday, October 7, 2017

How Do I Use "Switch" to Initialize a Variable or Constant?

This is a sample from my book in progress at LeanPub: What Every Programmer Needs to Know About Swift.

You might want to be able to use 'switch' to initialize a variable or constant, given 3 or more possible conditions (if it's just two, you can use the trinary operator ":?")
enum  Color {  // In this example, assume we can't associate 
    case red   // values with these cases _in_ this enum, perhaps
    case green // because we're not allowed to modify this code.
    case blue 
    case purple
}
let c = Color.green

// a one-line "switch expression" which doesn't exist in Swift.
let menuNumber = switch c { case .red: 1, case .green: 2, 
    case .blue: 3, default: 0 } // ILLEGAL SYNTAX
You can use a switch statement or if/else statements to initialize the value; the compiler knows you are initializing a constant within that logic. As long as in every code path before the constant is used, you initialize the constant once and only once.
let menuNumber : Int
switch c {
    case .red: menuNumber = 1
    case .green: menuNumber = 2
    case .blue: menuNumber = 3
    default: menuNumber = 0
}
print(menuNumber) // prints 2
You could also create a dictionary and subscript it in the same line of code:
// moral equivalent of a one-line "switch expression":
let menuNumber = [Color.red : 1, Color.green : 2, Color.blue : 3][c] ?? 0
print(menuNumber) // prints 2
We need "?? 0" because subscripting a dictionary returns an optional, which will be nil if the subscript value isn't found in the dictionary. The "??" operator returns the unwrapped value of the optional, if the optional isn't nil, and it returns the right-hand value, 0, if optional value is nil.
This is actually less code than "switch expression", but some people may find harder to read than the explicit logic of switch/if/else/etc. Use caution.

No comments:

Post a Comment