Monday, May 13, 2019

Associated Value for Swift Enum type

  1. Usually for simple enum type, it can defined as below. Each enum value can be used as constant definition. For example, if you define enum Barcode { case upc case qrCode } Then in your code, you can set var m = Barcode.upc or check whether a variable equals Barcode.upc or Barcode.grCode in a switch statement. In swift, enum type can also define associated type. When associated type is defined for enum type, then each enum instance must specify the value of the associated types. In this sense, the enum variable with associated type is more like an object with properties. Associated type can be easily accessed from switch statement as shown below enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) } var productBarcode = Barcode.upc(8, 85909, 51226, 3) var productBarcode2 = .qrCode("ABCDEFGHIJKLMNOP") switch productBarcode { case .upc(let numberSystem, let manufacturer, let product, let check): print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).") case .qrCode(let productCode): print("QR code: \(productCode).") }

Note, in the below code, the type of v and vv are different

        let v = Barcode.upc . //type of v is (Int, Int, Int, Int) -> Barcode
        let vv = Barcode.upc(1, 2, 3, 4) . //type of vv is upc(1, 2, 3, 4)



Optional type is a special usage of enum. In swift, Optional is defined as
enum Optional<Wrapped> {
case none
  case some(Wrapped)
}
nil is just a shortened form of Optional.none.
SomeType? is a shorted form of Optional<SomeType>.
Sometime, it is needed to use the original Optional type to set the nested optional value, such as, setting String??'s value to a String? object whose value is nil as shown below

let s1: String?? = Optional.some(nil)
let s2 :String?? = .none
print(String(describing: s1))
if let s3 = s2 {
    print("s3 is \(String(describing: s3))")
    if let s4 = s3 {
        print("sssnil is \(String(describing: s4))")
    }
    else {
        print("s3's value is nil")
    }
}


No comments:

Post a Comment