'subscript' is unavailable: cannot subscript String with a CountableClosedRange, see the documentation comment for discussion

前端 未结 8 833
谎友^
谎友^ 2021-01-31 13:57

In Swift 4, I\'m getting this error when I try to take a Substring of a String using subscript syntax.

\'subscript\' is unavaila

8条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 14:36

    Building on both p-sun's and Justin Oroz's answers, here are two extensions that protect against invalid indexes beyond the start and end of a string (these extensions also avoid rescanning the string from the beginning just to find the index at the end of the range):

    extension String {
    
        subscript(bounds: CountableClosedRange) -> String {
            let lowerBound = max(0, bounds.lowerBound)
            guard lowerBound < self.count else { return "" }
    
            let upperBound = min(bounds.upperBound, self.count-1)
            guard upperBound >= 0 else { return "" }
    
            let i = index(startIndex, offsetBy: lowerBound)
            let j = index(i, offsetBy: upperBound-lowerBound)
    
            return String(self[i...j])
        }
    
        subscript(bounds: CountableRange) -> String {
            let lowerBound = max(0, bounds.lowerBound)
            guard lowerBound < self.count else { return "" }
    
            let upperBound = min(bounds.upperBound, self.count)
            guard upperBound >= 0 else { return "" }
    
            let i = index(startIndex, offsetBy: lowerBound)
            let j = index(i, offsetBy: upperBound-lowerBound)
    
            return String(self[i..

提交回复
热议问题