gpt4 book ai didi

Swift3 & Xcode8 : ’subscript' is unavailable: cannot subscript String with a CountableClosedRange,

转载 作者:IT王子 更新时间:2023-10-29 05:33:05 28 4
gpt4 key购买 nike

错误 1:当我尝试从元数据中获取 stringValue 时,在 Swift3 中显示上述错误:

let myMetadata: AVMetadataMachineReadableCodeObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

// take out the system and check-digits
let myBarcode = myMetadata.stringValue[1...11] //error

错误 2:在 String 的扩展中,我编写了这些以获取 right(x)left(x) 函数以获取子字符串:

extension String {

// length of string
var length: Int {
return self.characters.count
}

// right(x) and left(x) function to get substring
func right(_ i: Int) -> String?
{
return self[self.length-i ... self.length-1 ] //error
}

func left(_ i: Int) -> String?
{
return self[0 ... i-1] //error
}
}

enter image description here

最佳答案

将此扩展用于可数闭区间 [0...4] 下标

extension String {

subscript (r: CountableClosedRange<Int>) -> String {
get {
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.index(startIndex, offsetBy: r.upperBound - r.lowerBound)
return self[startIndex...endIndex]
}
}
}

或更安全的版本,它检查边界并返回 nil 而不是超出范围的异常:

extension String {

subscript (r: CountableClosedRange<Int>) -> String? {
get {
guard r.lowerBound >= 0, let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound, limitedBy: self.endIndex),
let endIndex = self.index(startIndex, offsetBy: r.upperBound - r.lowerBound, limitedBy: self.endIndex) else { return nil }
return self[startIndex...endIndex]
}
}
}

Swift 4 的变化:你需要从结果中创建一个新的字符串

return String(self[startIndex...endIndex])

关于Swift3 & Xcode8 : ’subscript' is unavailable: cannot subscript String with a CountableClosedRange<Int>,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39611841/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com