Swift 4:>>运营商不可用 在Swift 4.0中寻找将HexColor转换为UIColor的替换运算符:
以下是Swift 3.0中早期代码版本的示例代码。
public extension UIColor {
convenience init(hex: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if hex.hasPrefix("#") {
let index = hex.characters.index(hex.startIndex, offsetBy: 1)
let hex = hex.substring(from: index)
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "")
}
} else {
// print("Scan hex error")
}
} else {
// print("Invalid RGB string, missing '#' as prefix", terminator: "")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
提前致谢。
答案 0 :(得分:0)
此代码在Swift 4中与>>
运算符没有任何问题。唯一的问题是字符串处理。我可以替换
let index = hex.characters.index(hex.startIndex, offsetBy: 1)
let hex = hex.substring(from: index)
与
let index = hex.index(hex.startIndex, offsetBy: 1)
let hex = String(hex[index...])
就个人而言,我会对该例程进行一些其他更改:
我会使它成为可用的初始值设定项(例如init?(...)
返回可选项)。现在,调用代码无法知道转换为UIColor
是否失败。
我将简化上面的字符串处理,将其缩小为:
let hex = hex.replacingOccurrences(of: "^#", with: "", options: .regularExpression)
这不仅会将其减少到一行,而且还会删除任何前导#
,但这也意味着如果您传递一个不具有前导{的十六进制字符串,此代码现在也会起作用{ {1}}。
我使用#
代替扫描仪。它只是更简单一点。
因此:
UInt64(_:radix:)