【问题标题】:'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead in swift'subscript(_:)' 不可用:不能用 Int 为 String 下标,在 swift 中使用 String.Index 代替
【发布时间】:2021-11-26 01:18:00
【问题描述】:

这是我的代码:

let textRange = UETextRange(charIndex: i, length: l - i)
for j in textRange.charIndex...getCharIndexAfterEndOfRange(range: textRange) {   
    if String(initialText[j - 1]) == "\n" { //error here
        hits += 1
        let hitIndex = attributeRange.index + (hits - 1)
        if hitIndex <= paragraphStyles.count {
            let charIndex = paragraphStyles[hitIndex].charIndex
        }
    }
}

我该如何解决这个错误?

【问题讨论】:

    标签: swift string


    【解决方案1】:

    在 Swift 中访问 String 的元素与大多数语言的工作方式略有不同。 Swift 的String 下标需要String.Index(不是Int),如文档所示:

    @inlinable public subscript(i: String.Index) -> Character { get }
    

    我们想要做的是获取startIndex,将其偏移我们想要的整数索引,然后从字符串中获取 that 索引。固定代码:

    let char = initialText[initialText.index(initialText.startIndex, offsetBy: j - 1)]
    
    if char == "\n" {
        /* ... */
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2014-10-09
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多