扩展可以向已有类型添加新的构造器。这可以让你扩展其它类型,将你自己的定制类型作为构造器参数,或者提供该类型的原始实现中没有包含的额外初始化选项。
扩展能向类中添加新的便利构造器,但是它们不能向类中添加新的指定构造器或析构函数。指定构造器和析构函数必须总是由原始的类实现来提供。
import UIKit
extension UIColor {
class func randomColor() -> UIColor {
return UIColor(red: CGFloat(arc4random_uniform(256))/255.0, green: CGFloat(arc4random_uniform(256))/255.0, blue: CGFloat(arc4random_uniform(256))/255.0, alpha: 1.0)
}
/// 便利构造函数
/// 在extensino扩充构造函数,必须扩充便利构造函数
/// 1. 必须在init前加上convenience
/// 2. 必须调用self.init()原有的某一个构造函数
/// - Parameters:
/// - r: 红
/// - g: 绿
/// - b: 蓝
/// - a: 透明度
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
/// 便利构造函数 (十六进制转UIColor)
/// init? 返回值可为空
convenience init?(hexString: String) {
guard hexString.characters.count >= 6 else {
return nil
}
var hexTempString = hexString.uppercased()
if hexTempString.hasPrefix("0X") || hexTempString.hasPrefix("##") {
hexTempString = (hexTempString as NSString).substring(from: 2)
}
if hexTempString.hasPrefix("#") {
hexTempString = (hexTempString as NSString).substring(from: 1)
}
var range = NSRange(location: 0, length: 2)
let rHex = (hexTempString as NSString).substring(with: range)
range.location = 2
let gHex = (hexTempString as NSString).substring(with: range)
range.location = 4
let bHex = (hexTempString as NSString).substring(with: range)
var r: UInt32 = 0
var g: UInt32 = 0
var b: UInt32 = 0
Scanner(string: rHex).scanHexInt32(&r)
Scanner(string: gHex).scanHexInt32(&g)
Scanner(string: bHex).scanHexInt32(&b)
self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b))
}
}