enum MyEnum: CaseIterable { case case1(Int) case case2(String) case case3(Double) static var allCases: [MyEnum] { var cases: [MyEnum] = [] for item in MyEnum.allValues { cases.append(item) } return cases } private static var allValues: [MyEnum] { return [ .case1(10)...
CaseIterable 如同 Equatable 和 Hashable 一样,是泛型约束,而不是泛型类型,它的具体定义如下: publicprotocol CaseIterable{/// A type that can represent a collection of all values of this type.associatedtype AllCases:Collection where Self.AllCases.Element==Self/// A collection of all values of this ...
符合CaseIterable 协议的类型通常是没有关联值的枚举。当使用 CaseIterable 类型时,可以通过该类型的 allCases 属性访问所有枚举值的集合。 例如,以下示例中声明的 CompassDirection 枚举符合 CaseIterable 协议。你可以通过 CompassDirection.allCases 访问枚举值的数量和枚举值本身。 enum CompassDirection: CaseIterable { ...
符合CaseIterable协议的类型通常是没有关联值的枚举。使用CaseIterable类型时,您可以使用类型的allCases属性访问所有类型案例的集合。 例如,此示例中声明的CompassDirection枚举符合CaseIterable。您可以通过CompassDirection.allCases访问案例数量和案例本身。 enumCompassDirection:CaseIterable{casenorth, south, east, west } pri...
enumWeek: CaseIterable { caseSun caseMon caseTue caseWen caseThu caseFri caseSat } print(Week.allCases) //也可以重写allCases方法 enumWeek2: CaseIterable { caseSun caseMon caseTue caseWen caseThu caseFri caseSat staticvarallCases: [Week2]{ ...
CaseIterable的存在允许您以编程方式遍历enum的所有可能情况,允许您使用enum类型作为其情况的Collection:
Types that conform to the CaseIterable protocol are typically enumerations without associated values. When using a CaseIterable type, you can access a collection of all of the type’s cases by using the type’s allCases property. For example, the CompassDirection enumeration declared in this examp...
总结 CaseIterable 是一个非常有用的协议,可使遵循协议的枚举变得可迭代,并允许您使用 allCases 访问所有情况。使用 CaseIterable 协议可改善代码的可读性,并使维护更加容易。
这也是一种黑客行为,但你可以看到正则表达式构建器在SWIFT进化提案中是如何工作的:
这也是一种黑客行为,但你可以看到正则表达式构建器在SWIFT进化提案中是如何工作的: