I've thought of two types of implementation; which one of them is better in your opinion in terms of performance, readability and maintainability?
Create an extension of UIColor like this
extension UIColor {
class func myColor() -> UIColor {
return UIColor(red: 128/255, green: 102/255, blue: 0, alpha: 1)
}
}
Create a structure:
struct Colors {
static let myColor = UIColor(red: 255/255, green: 102/255, blue: 0, alpha: 1)
}
Answer: Extension, in my professional opinion.
Think about it; you are, in philosophy, 'extending' the range of colors offered by UIColor
. Provided that your color name is distinct and the new function follows Apple's method naming protocol (i.e. <color name>Color
), extending UIColor
seems neater. One or two new colors (in my opinion) don't warrant an entire dedicated struct
.
Bonus answer:
Where would a struct
(or enum
!) be a good fit?
enum
, to serve as a concrete list for available options. sharkBlueColor
, anyone?).... the list goes on. You must learn to discern and decide for yourself as you mature as a Swift developer!
I use enums for this
enum AppColor: UInt32 {
case DarkBlue = 0x00437C
case LightBlue = 0x7CCEF0
var color: UIColor {
return UIColor(hex: rawValue)
}
}
This way it is easy to reuse same color in xib
/storyboard
because I have hex values ready for copy/paste. And also less code needed for defining new color
For creating colors from hex value I used UIColor
extension:
extension UIColor {
public convenience init(hex: UInt32) {
let mask = 0x000000FF
let r = Int(hex >> 16) & mask
let g = Int(hex >> 8) & mask
let b = Int(hex) & mask
let red = CGFloat(r) / 255
let green = CGFloat(g) / 255
let blue = CGFloat(b) / 255
self.init(red:red, green:green, blue:blue, alpha:1)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With