Created
January 2, 2019 06:44
-
-
Save ethanhuang13/5aae1d11beed58257c0fa5261792f7eb to your computer and use it in GitHub Desktop.
@dynamicMemberLookup example
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
// An (useless) example of Swift 4.2 @dynamicMemberLookup attributes. | |
// let color1 = HexColor().cbcbcb | |
// let color2 = HexColor().000000 // This can also be built. Will be treat as "000000" | |
import Foundation | |
@dynamicMemberLookup | |
struct HexColor { | |
subscript(dynamicMember member: String) -> UIColor? { | |
do { | |
let regex = try NSRegularExpression(pattern: "^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$", options: []) | |
let results = regex.matches(in: member, options: [], range: NSRange(member.startIndex..., in: member)) | |
guard let hexString = results.map ({ (member as NSString).substring(with: $0.range) }).first else { | |
return nil | |
} | |
var hexValue: UInt32 = 0 | |
guard Scanner(string: hexString).scanHexInt32(&hexValue) else { | |
return nil | |
} | |
switch hexString.count { | |
case 6: | |
return UIColor(hex6: hexValue) | |
case 8: | |
return UIColor(hex8: hexValue) | |
default: | |
return nil | |
} | |
} catch { | |
return nil | |
} | |
} | |
} | |
// Copied and modified from https://github.com/yeahdongcn/UIColor-Hex-Swift/blob/master/HEXColor/UIColorExtension.swift | |
extension UIColor { | |
convenience init(hex6: UInt32, alpha: CGFloat = 1) { | |
let red = CGFloat((hex6 & 0xFF0000) >> 16) | |
let green = CGFloat((hex6 & 0x00FF00) >> 8) | |
let blue = CGFloat( hex6 & 0x0000FF) | |
let divisor: CGFloat = 255 | |
self.init(red: red / divisor, | |
green: green / divisor, | |
blue: blue / divisor, | |
alpha: alpha) | |
} | |
convenience init(hex8: UInt32) { | |
let red = CGFloat((hex8 & 0xFF000000) >> 24) | |
let green = CGFloat((hex8 & 0x00FF0000) >> 16) | |
let blue = CGFloat((hex8 & 0x0000FF00) >> 8) | |
let alpha = CGFloat(hex8 & 0x000000FF) | |
let divisor: CGFloat = 255 | |
self.init(red: red / divisor, | |
green: green / divisor, | |
blue: blue / divisor, | |
alpha: alpha / divisor) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment