我正在尝试在 UIColor
上实现 IntegerLiteralConvertible 协议(protocol)。我真正想做的是这个
let black: UIColor = 0x000000
我首先尝试关注这里的 swift 博客 https://developer.apple.com/swift/blog/?id=8这不能开箱即用。看来根据 swift in Flux https://github.com/ksm/SwiftInFlux#literalconvertible-protocols-use-constructor他们不再使用convertFromIntegerLiteral,而是使用初始化器。因此,这就是我们应该拥有的:
extension UIColor: IntegerLiteralConvertible {
public convenience init(integerLiteral value: IntegerLiteralType) {
UIColor(red: 1, green: 0, blue: 0, alpha: 1)
}
}
但是初始值设定项内部又是什么呢?我无法 self 设定。我想说这样的话
self.init(red: 0, green: 0, blue: 0, alpha: 1)
这不起作用,其他任何事情似乎也不起作用。我收到错误“初始化程序要求 init(IntegerLiteral) 只能通过非最终类“UIColor”定义中的“必需”初始化程序来满足”,这不是很有帮助。关于如何实现这项工作有什么想法吗?
最佳答案
这是 Swift 2.0 的(解决方法)代码:
public class Color: UIColor, IntegerLiteralConvertible {
public typealias IntegerLiteralType = UInt32
public required init(integerLiteral value: IntegerLiteralType) {
let a = CGFloat((value & 0xFF000000) >> 24) / 255.0
let r = CGFloat((value & 0xFF0000) >> 16) / 255.0
let g = CGFloat((value & 0xFF00) >> 8) / 255.0
let b = CGFloat((value & 0xFF)) / 255.0
super.init(red: r, green: g, blue: b, alpha: a)
}
required public init(colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) {
super.init(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
关于Swift 实现 LiteralConvertible 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26498391/