Search Your Question

How to iterate over all enum cases?

Ans : 

Swift 4.2's CaseIterable can help us avoid bugs and make our code more consistent when defining enum-keyed dictionaries. We'll start by making TextType conform to CaseIterable. Just like with Codable, Equatable and Hashable, we don't need to write any additional code ourselves - instead CaseIterable kind of acts as a marker for the compiler, telling it to synthesize an allCases collection for us:


enum TextType: CaseIterable {
    case title
    case subtitle
    case sectionTitle
    case body
    case comment
}


With the above change, we can now use TextType.allCases to access a collection of all cases in order, which we can then use to build up our fonts dictionary without the risk of missing a case, like this:


var fonts = [TextType : UIFont]()

for type in TextType.allCases {
    switch type {
    case .title:
        fonts[type] = .preferredFont(forTextStyle: .headline)
    case .subtitle:
        fonts[type] = .preferredFont(forTextStyle: .subheadline)
    case .sectionTitle:
        fonts[type] = .preferredFont(forTextStyle: .title2)
    case .body:
        fonts[type] = .preferredFont(forTextStyle: .body)
    case .comment:
        fonts[type] = .preferredFont(forTextStyle: .footnote)
    }
}


Definitely an improvement, since if we now add a new text type without a matching font definition - we'll get a compiler error 👍.


No comments:

Post a Comment