filter enum cases

๐Ÿ’พ ็จ‹ๅผ๏ผšpaiza.io

โฌ†๏ธ ้œ€่ฆ๏ผšCaseReflectable โญ๏ธ

// ------------
//     Enum
// ------------

// enum with associated values
// (conforms to `CaseReflectable`) โญ๏ธ 
enum Enum: CaseReflectable {
    case int(Int)
    case int2(Int)
    case person(name: String, age: Int)
    case str(String)
}

// ------------
//     main
// ------------

let a: Enum = .int(3)

Enum.int ~= a        // true
Enum.int2 ~= a       // false

let joe = Enum.person(name: "joe", age: 8)

Enum.person ~= joe   // true
Enum.int ~= joe      // false

// array of enum cases
let items: [Enum] = [
    .int(1), .str("hi"), .int(2)
]

// filter enum cases โญ๏ธ 
let filtered = items.filter { Enum.int ~= $0 }
print(filtered)      // [Enum.int(1), Enum.int(2)]

History

  1. ๅ‰›้–‹ๅง‹็š„่งฃๆณ•๏ผšไฝฟ็”จ switch case, if case.

Last updated