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

前端 未结 8 834
谎友^
谎友^ 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:35

    1. If you want to use subscripts on Strings like "palindrome"[1..<3] and "palindrome"[1...3], use these extensions.

    Swift 4

    extension String {
        subscript (bounds: CountableClosedRange) -> String {
            let start = index(startIndex, offsetBy: bounds.lowerBound)
            let end = index(startIndex, offsetBy: bounds.upperBound)
            return String(self[start...end])
        }
    
        subscript (bounds: CountableRange) -> String {
            let start = index(startIndex, offsetBy: bounds.lowerBound)
            let end = index(startIndex, offsetBy: bounds.upperBound)
            return String(self[start..

    Swift 3

    For Swift 3 replace with return self[start...end] and return self[start...

    1. Apple didn't build this into the Swift language because the definition of a 'character' depends on how the String is encoded. A character can be 8 to 64 bits, and the default is usually UTF-16. You can specify other String encodings in String.Index.

    This is the documentation that Xcode error refers to.

    More on String encodings like UTF-8 and UTF-16

提交回复
热议问题