Last active
March 9, 2020 13:40
-
-
Save dnedrow/a01307045de7d4d1d05f3996e43eefce to your computer and use it in GitHub Desktop.
This protocol defines functions related to hex string conversion.
This file contains hidden or 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
| // Created by Nedrow, David E on 3/25/19. | |
| // This work is licensed under Attribution 4.0 International (CC 4.0) | |
| import UIKit | |
| // MARK: - String+IntFromHex.swift | |
| /// This protocol defines functions related to hex string conversion. | |
| public protocol HexStringProtocol { | |
| /// Create an int from a given hex value string. | |
| /// | |
| /// - Parameter hexStr: String in the form "[#]XXXXXX" | |
| /// - Returns: The int value for the hex string. `nil` is returned for inputs that can not be converted. | |
| func intFromHexString() -> UInt32? | |
| } | |
| extension String: HexStringProtocol { | |
| public func intFromHexString() -> UInt32? { | |
| var hexInt: UInt32 = 0 | |
| // Make sure we only have strings that look like a normal [A]RGB hex value | |
| let regex = try? NSRegularExpression(pattern: "^[#]?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$", options: .caseInsensitive) | |
| if (regex?.matches(in: self, options: [], range: NSRange(location: 0, length: self.count)))?.count ?? 0 == 0 { | |
| return nil | |
| } | |
| let scanner: Scanner = Scanner(string: self.uppercased()) | |
| scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#") | |
| scanner.scanHexInt32(&hexInt) | |
| return hexInt != UInt.max ? hexInt : nil | |
| } | |
| } | |
| // This work is licensed under Attribution 4.0 International (CC 4.0) | |
| // You are free to: | |
| // Share — copy and redistribute the material in any medium or format | |
| // Adapt — remix, transform, and build upon the material | |
| // for any purpose, even commercially. | |
| // | |
| // This license is acceptable for Free Cultural Works. | |
| // The licensor cannot revoke these freedoms as long as you follow the license terms. | |
| // See https://creativecommons.org/licenses/by/4.0/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment