- iOS Programming Cookbook
- Hossam Ghareeb
- 325字
- 2021-07-09 18:29:39
How it works...
Now, you have a new type in your program called Monster, which takes one value of given four values. The values are defined with the case keyword followed by the value name. You have two options to list your cases; you can list each one of them in a separate line preceded by the case keyword, or you can list them in one line with a comma separation. I prefer using the first method, that is, listing them in separate lines, as we will see later that we can add raw values for cases that will be more clear while using this method.
If you come from a C or Objective-C background, you know that the enums values are mapped to integer values. In Swift, it's totally different, and they aren't explicitly equal to integer values.
The first variable monster1 is created using the enum name followed by '.' and then the type that you want. Once monster1 is initialized, its type is inferred with Monster; so, later you can see that when we changed its value to Bear, we have just used the '.' operator as the compiler already knows the type of monster1. However, this is not the only way that you will use enums. Since enums is a group of related values, so certainly you will use it with control flow to perform specific logic based on its value. The switch statement is your best friend in that case as we saw in the monsterPowerFromType() function.
We've created a function that returns the monster power based on its type. The switch statement checks all values of monster with '.' followed by an enum value. As you already know, the switch statement is exhaustive in Swift and should cover all possible values; of course, you can use default in case it's not possible to cover all, as we saw in the canMonsterSwim() function. The default statement captures all non-addressed cases.
- Learning OpenDaylight
- Linux系統架構與運維實戰
- Modern Web Testing with TestCafe
- UNIX操作系統設計
- Mastering Distributed Tracing
- Haskell Financial Data Modeling and Predictive Analytics
- Linux使用和管理指南:從云原生到可觀測性
- Mastering Reactive JavaScript
- 計算機系統:基于x86+Linux平臺
- μC/OS-III內核實現與應用開發實戰指南:基于STM32
- 大學計算機應用基礎實踐教程(Windows 7+MS Office 2010)
- bash shell腳本編程經典實例(第2版)
- Linux從入門到精通(視頻教學版)
- VMware vSphere 5.1 Cookbook
- 操作系統之哲學原理第2版