Last active
August 21, 2020 19:50
-
-
Save helbertgs/2f2d8c6304b7cd490ae96f407e802218 to your computer and use it in GitHub Desktop.
Create struct by string literal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
struct ColorHex: ExpressibleByStringLiteral { | |
// MARK: - Type Alias. | |
typealias StringLiteralType = String | |
// MARK: - Private Property(ies). | |
private var _value: String | |
// MARK: - Public Property(ies). | |
private(set) var red: CGFloat = 0 | |
private(set) var blue: CGFloat = 0 | |
private(set) var green: CGFloat = 0 | |
private(set) var alpha: CGFloat = 0 | |
var hex: String { | |
_value | |
} | |
var uiColor: UIColor { | |
.init(red: red, green: green, blue: blue, alpha: alpha) | |
} | |
var cgColor: CGColor { | |
.init(red: red, green: green, blue: blue, alpha: alpha) | |
} | |
var ciColor: CIColor { | |
.init(red: red, green: green, blue: blue, alpha: alpha) | |
} | |
// MARK: - Constructor(s). | |
init(stringLiteral value: String) { | |
_value = value | |
if hex.hasPrefix("#") && value.count == 7 { | |
let start = hex.index(hex.startIndex, offsetBy: 1) | |
let hexColor = String(hex[start...]) | |
let scanner = Scanner(string: hexColor) | |
var hexNumber: UInt64 = 0 | |
if scanner.scanHexInt64(&hexNumber) { | |
red = CGFloat((hexNumber & 0xff0000) >> 16) / 255 | |
green = CGFloat((hexNumber & 0x00ff00) >> 8) / 255 | |
blue = CGFloat(hexNumber & 0x0000ff) / 255 | |
} | |
} else { | |
fatalError("Invalid value!") | |
} | |
} | |
} | |
extension ColorHex: CustomDebugStringConvertible { | |
var debugDescription: String { _value } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment