- iOS Programming Cookbook
- Hossam Ghareeb
- 257字
- 2021-07-09 18:29:39
Enums with associated values
Last but not least, we will talk about another feature in Swift enums, which is creating enums with associated values. Associated values let you store extra information with enum case value. Let's take a look at the problem and how we can solve it using associated values in enums.
Suppose we are working with an app that works with products, and each product has a code. Some products codes are represented by QR code format, but others by UPC format. Check out the following image to see the differences between two codes at http://www.mokemonster.com/websites/erica/wp-content/uploads/2014/05/upc_qr.png):
The UPC code can be represented by four integers; however, QR code can be represented by a string value. To create an enum to represent these two cases, we would do something like this:
enum ProductCode{ case UPC(Int, Int, Int, Int) case QR(String) } var productCode = ProductCode.UPC(4, 88581, 1497, 3) productCode = ProductCode.QR("BlaBlaBla")
First, UPC is a case, which has four integer values, and the second is a QR, which has a string value. Then, you can create enums the same way we created before in other enums, but here you just have to pass parameters for the enum. When you need to check the value of enum with its associated value, we will use a switch statement as usual, but with some tweaks:
switch productCode{ case .UPC(let numberSystem, let manufacturerCode, let productCode, let checkDigit): print("Product UPC code is \(numberSystem) \(manufacturerCode) \(productCode) \(checkDigit)") case .QR(let QRCode): print("Product QR code is \(QRCode)") } // "Product QR code is BlaBlaBla"
- Linux運維之道(第3版)
- 構建高可用Linux服務器(第4版)
- Linux系統文件安全實戰全攻略
- Mobile-first Bootstrap
- Haskell Financial Data Modeling and Predictive Analytics
- Linux集群和自動化運維
- Android物聯網開發細致入門與最佳實踐
- Linux內核設計的藝術:圖解Linux操作系統架構設計與實現原理
- Linux服務器配置與管理
- iOS 8開發指南
- Windows 8實戰從入門到精通(超值版)
- 從實踐中學習Windows滲透測試
- μC/OS-III內核實現與應用開發實戰指南:基于STM32
- UI設計手繪表現從入門到精通
- Implementing Domain-Specific Languages with Xtext and Xtend(Second Edition)