swift的enum基础

其它语言的枚举:

符号化的整型常量的集合;

swift的枚举:

可以是任何基础类型和无类型;

If you are familiar with C, you will know that C enumerations assign related names to a set of integer values. Enumerations in Swift are much more flexible, and don’t have to provide a value for each case of the enumeration. If a value (known as a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.

一、enum的类型:

enum defaultRawValue:String{}

enum TestEnum{

    case goFun(para:String)

    case doFun(para:String, para1:String)

}

二、rawValue:

具有类型的枚举对象具有rawValue;

数值类型的缺省值为:0、1 …

字符串类型的缺省rawValue为字符串本身;

三、具有关联值的枚举

  • enum Barcode {
  •     case upc(Int, Int, Int, Int)
  •     case qrCode(String)
  • }

“Define an enumeration type called Barcode, which can take either a value of upc with an associated value of type (Int, Int, Int, Int), or a value of qrCode with an associated value of type String.”

要区别枚举变量和关联值

枚举变量参与枚举运算;

关联值和rawvalue不参与。

四、枚举的初始化

1、非关联类型的枚举变量可以使用枚举值直接初始化;

2、有rawValue的枚举类型变量可以使用let possiblePlanet = Planet(rawValue: 7) 初始化;

3、有关联值的枚举值需要先对枚举值本身初始化,然后执行枚举变量初始化;

var productBarcode = Barcode.upc(8, 85909, 51226, 3)

五、枚举使用:

1、普通使用switch;

2、有关联值的使用:

  • switch productBarcode {
  • case let .upc(numberSystem, manufacturer, product, check):
  •     print("UPC : (numberSystem), (manufacturer), (product), (check).")
  • case let .qrCode(productCode):
  •     print("QR code: (productCode).")
  • }

3、if语句使用(赋值):条件选择使用

if case let .stream(inputStream, _) = uploadable {

                upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream }

            }

if case .pending = box.inspect() {

            print("PromiseKit: warning: pending promise deallocated")

        }

原文地址:https://www.cnblogs.com/feng9exe/p/10444828.html