Skip to content

Instantly share code, notes, and snippets.

@jancassio
Last active November 15, 2021 03:15
Show Gist options
  • Save jancassio/a4c2d506e0772e5c5e907834095eb8e1 to your computer and use it in GitHub Desktop.
Save jancassio/a4c2d506e0772e5c5e907834095eb8e1 to your computer and use it in GitHub Desktop.
FontFamily protocol helps to enumerate and access font face strongly typed.

FontFamily Enumerated (Swift)

Helps to quick enumarate font faces by strong typed enumerators.

Usage

enum Arial: String, FontFamily {
  case regular = "Arial-Regular"
  case bold = "Arial-Bold"
  case italic = "Arial-Italic"
  case extraBold = "Arial-ExtraBold"
}

// using strong typed font family:
let bodyFont = Arial.regular.withSize(12)
let titleFont = Arial.bold.withSize(26)

License

MIT

/*
FontFamily.swift
MIT License
Copyright (c) 2020 Jan Cassio
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import SwiftUI
/**
* Provide a strong typed API for enumerated font family.
*
* FontFamily protocol enable easy font family setup using enumerators of string type
* that just need to match the family name of desired font.
*
* ```
* enum Arial: String, FontFamily {
* case regular = "Arial-Regular"
* case bold = "Arial-Bold"
* case italic = "Arial-Italic"
* case extraBold = "Arial-ExtraBold"
* }
*
* // using strong typed font family:
* let bodyFont = Arial.regular.withSize(12)
* let titleFont = Arial.bold.withSize(26)
* ```
*/
fileprivate protocol FontFamily {
var fontName: String { get }
func withSize(_ size: CGFloat) -> Font
}
extension FontFamily where Self: RawRepresentable, RawValue == String {
var fontName: String {
self.rawValue
}
func withSize(_ size: CGFloat) -> Font {
Font.custom(fontName, size: size)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment