Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

Error 1: When I am trying get the stringValue from Metadata shows above error in Swift3:

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

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

Error 2: In extensions of String I write these to get right(x) and left(x) function to get substring:

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

like image 380
Sanju Avatar asked Sep 21 '16 08:09

Sanju


1 Answers

Use this extension for the countable closed range [0...4] subscripting

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]
    }
  }
}

or a safer version which checks the bounds and returns nil rather than an out-of-range exception:

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 change: You need to create a new string from the result

return String(self[startIndex...endIndex])
like image 128
vadian Avatar answered Oct 15 '22 22:10

vadian