官术网_书友最值得收藏!

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" 
主站蜘蛛池模板: 宣城市| 宁明县| 安顺市| 灵璧县| 正阳县| 昭平县| 宾阳县| 乌苏市| 远安县| 红河县| 江门市| 巴里| 恩施市| 集贤县| 临西县| 来宾市| 探索| 济宁市| 迁安市| 广元市| 曲水县| 安丘市| 南川市| 诏安县| 建湖县| 新巴尔虎右旗| 信宜市| 福鼎市| 甘孜县| 阿拉善右旗| 尉犁县| 宝山区| 宁河县| 永春县| 郓城县| 渝中区| 施秉县| 贵南县| 乌鲁木齐县| 丽水市| 鸡西市|