Reputation: 145
I'm declaring UIColors in an extension: UIColor file but I keep getting error like "instance member 'red' cannot be used on type 'UIColor', when I declared it already in the extension file. I will list a picture of the error and the code below.
Extension UIColor File
import Foundation
import UIKit
extension UIColor {
var red: CGFloat {
get {
let components = self.cgColor.components
return components![0]
}
}
var green: CGFloat {
get {
let components = self.cgColor.components
return components![1]
}
}
var blue: CGFloat {
get {
let components = self.cgColor.components
return components![2]
}
}
var alpha: CGFloat {
get {
return self.cgColor.alpha
}
}
func alpha(_ alpha: CGFloat) -> UIColor {
return UIColor(red: self.red, green: self.green, blue: self.blue, alpha: alpha)
}
func white(_ scale: CGFloat) -> UIColor {
return UIColor(
red: self.red + (1.0 - self.red) * scale,
green: self.green + (1.0 - self.green) * scale,
blue: self.blue + (1.0 - self.blue) * scale,
alpha: 1.0
)
}
}
Swift file where I would like to use one of the colors.
var color: UIColor = UIColor.red {
didSet {
setup()
}
}
Upvotes: 1
Views: 648
Reputation: 318774
The red
, green
, and blue
property names you added in your extension conflict with the class variables of the same names. Rename the properties in your extension.
FYI - there is no need for your alpha
method in your extension. UIColor
already provides the same method (named withAlphaComponent
).
And your implementation of red
, green
, and blue
may crash. You are assuming the CGColor
always has 3 components and you assume it is an RGB color. Neither case is always true.
Upvotes: 2