Skip to content

Instantly share code, notes, and snippets.

@damodarnamala
Created July 12, 2021 10:41
Show Gist options
  • Save damodarnamala/937d2b1795a992950050ff4e36091f40 to your computer and use it in GitHub Desktop.
Save damodarnamala/937d2b1795a992950050ff4e36091f40 to your computer and use it in GitHub Desktop.
Swift EnumMap
enum TextType: CaseIterable {
case title
case subtitle
case sectionTitle
case body
case comment
}
struct EnumMap<Enum: CaseIterable & Hashable, Value> {
private let values: [Enum : Value]
init(resolver: (Enum) -> Value) {
var values = [Enum : Value]()
for key in Enum.allCases {
values[key] = resolver(key)
}
self.values = values
}
subscript(key: Enum) -> Value {
return values[key]!
}
}
let fonts = EnumMap<TextType, UIFont> { type in
switch type {
case .title:
return .preferredFont(forTextStyle: .headline)
case .subtitle:
return .preferredFont(forTextStyle: .subheadline)
case .sectionTitle:
return .preferredFont(forTextStyle: .title2)
case .body:
return .preferredFont(forTextStyle: .body)
case .comment:
return .preferredFont(forTextStyle: .footnote)
}
}
let titleFont = fonts[.title]
print(titleFont)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment