.為了代碼的方便性,在objective-C可以自定義返回值為id和instancetype類型的類方法吻育,也叫+方法,而在swift中,我們可以定義便利構(gòu)造器,關(guān)鍵字convenience.
.比如我們?cè)诮oview設(shè)置自定義背景顏色或者給文字設(shè)置自定義字體顏色等時(shí)鸽心,UI給我們的顏色值往往是一些類似于"fc5912"或者"FC5912"的16進(jìn)制的數(shù)字串,為了方便,我們就需要傳相應(yīng)的顏色值去得到UIColor對(duì)象,這時(shí)候便利構(gòu)造器就派上用場(chǎng)了居暖。示例代碼如下:
extension UIColor {
convenience init(_ red: Int, _ green: Int, _ blue: Int, _ alpha: CGFloat = 1.0) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
}
convenience init(_ hexValue:Int) {
self.init((hexValue >> 16) & 0xff, (hexValue >> 8) & 0xff, hexValue & 0xff)
}
}
//699F38 105 159 56
let titleColor = UIColor(105, 159, 56)
let backColor = UIColor(0x699f38)