不推荐使用“substring(from:)":请使用带有“partial range from"运算符的字符串切片下标.斯威夫特 4 错误 [英] 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator. Swift 4 Error
问题描述
我正在将我现有的应用程序从 Swift 3
转换为 Swift 4
.它给出了错误:
I am converting my existing app from Swift 3
to Swift 4
. It is giving the error:
'substring(from:)' 已弃用:请使用带有部分范围 from"运算符的字符串切片下标.
'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
和
'characters' 已弃用:请直接使用 String 或 Substring
'characters' is deprecated: Please use String or Substring directly
我的 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' is deprecated: Please use String or Substring directly
'characters' is deprecated: Please use String or Substring directly
为此,您可以在 swift 4 中直接遍历字符串,因此无需字符数组.
For this you can directly loop through string in swift 4 so there is no need to characters array.
为了
'substring(from:)' 已弃用:请使用带有部分范围 from"运算符的字符串切片下标.
'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
参考 如何在斯威夫特 4?
这篇关于不推荐使用“substring(from:)":请使用带有“partial range from"运算符的字符串切片下标.斯威夫特 4 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!