Skip to content

Instantly share code, notes, and snippets.

@mrugeshtank
Created September 11, 2018 05:57
Show Gist options
  • Save mrugeshtank/e96d94e2df8f2bdc6fe7f66771e4a786 to your computer and use it in GitHub Desktop.
Save mrugeshtank/e96d94e2df8f2bdc6fe7f66771e4a786 to your computer and use it in GitHub Desktop.
enum CaseIterable for fonts enum
import Foundation
import UIKit
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]!
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
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]
let subtitleFont = fonts[.subtitle]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment