“下标"不可用:不能使用 CountableClosedRange<Int> 对字符串进行下标,请参阅文档注释以进行讨论 [英] &#39;subscript&#39; is unavailable: cannot subscript String with a CountableClosedRange&lt;Int&gt;, see the documentation comment for discussion

查看:23
本文介绍了“下标"不可用:不能使用 CountableClosedRange<Int> 对字符串进行下标,请参阅文档注释以进行讨论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 4 中,当我尝试使用下标语法获取 StringSubstring 时出现此错误.

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

'subscript' 不可用:不能对带有 CountableClosedRange 的字符串进行下标,请参阅文档注释进行讨论

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

例如:

let myString: String = "foobar"
let mySubstring: Substring = myString[1..<3]

两个问题:

  1. 我该如何解决这个错误?
  2. 错误中提到的用于讨论的文档评论"在哪里?

推荐答案

  1. 如果你想在像 "palindrome"[1..<3]"palindrome"[1...3] 这样的字符串上使用下标,请使用这些扩展.
  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<Int>) -> String {
        let start = index(startIndex, offsetBy: bounds.lowerBound)
        let end = index(startIndex, offsetBy: bounds.upperBound)
        return String(self[start...end])
    }

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

Swift 3

对于 Swift 3,替换为 return self[start...end]return self[start..<end].

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

  1. Apple 没有将其构建到 Swift 语言中,因为字符"的定义取决于字符串的编码方式.一个字符可以是 8 到 64 位,默认通常是 UTF-16.您可以在 String.Index 中指定其他字符串编码.
  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.

这是文档 Xcode 错误所指.

This is the documentation that Xcode error refers to.

更多关于 UTF-8 和 UTF 等字符串编码-16

这篇关于“下标"不可用:不能使用 CountableClosedRange<Int> 对字符串进行下标,请参阅文档注释以进行讨论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆