"子字符串(from:)"已弃用:请使用带有"部分范围from"运算符的字符串切片下标。迅捷 4 错误



我正在将现有应用程序从Swift 3转换为Swift 4。它给出了错误:

不赞成使用"substring(from:)":请使用带"partial range from"运算符的字符串切片下标。

"字符"已弃用:请直接使用字符串或子字符串

我的Swift 3代码是:

public convenience init?(hexString: String, alpha: Float) {
var hex = hexString
// Check for hash and remove the hash
if hex.hasPrefix("#") {
hex = hex.substring(from: hex.characters.index(hex.startIndex, offsetBy: 1))
}
if (hex.range(of: "(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .regularExpression) != nil) {
// Deal with 3 character Hex strings
if hex.characters.count == 3 {
let redHex   = hex.substring(to: hex.characters.index(hex.startIndex, offsetBy: 1))
let greenHex = hex.substring(with: (hex.characters.index(hex.startIndex, offsetBy: 1) ..< hex.characters.index(hex.startIndex, offsetBy: 2)))
let blueHex  = hex.substring(from: hex.characters.index(hex.startIndex, offsetBy: 2))
hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
}
let redHex = hex.substring(to: hex.characters.index(hex.startIndex, offsetBy: 2))
let greenHex = hex.substring(with: (hex.characters.index(hex.startIndex, offsetBy: 2) ..< hex.characters.index(hex.startIndex, offsetBy: 4)))
let blueHex = hex.substring(with: (hex.characters.index(hex.startIndex, offsetBy: 4) ..< hex.characters.index(hex.startIndex, offsetBy: 6)))
var redInt:   CUnsignedInt = 0
var greenInt: CUnsignedInt = 0
var blueInt:  CUnsignedInt = 0
Scanner(string: redHex).scanHexInt32(&redInt)
Scanner(string: greenHex).scanHexInt32(&greenInt)
Scanner(string: blueHex).scanHexInt32(&blueInt)
self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha))
}
else {
self.init()
return nil
}
}

如何将其转换为Swift 4

"characters"已弃用:请直接使用字符串或子字符串

为此,您可以直接在swift 4中循环字符串,这样就不需要字符数组。

对于

不赞成使用"substring(from:)":请使用带"partial range from"运算符的字符串切片下标。

请参阅Swift 4中如何使用字符串切片下标?

最新更新