字符串下标错误

时间:2017-09-25 16:01:21

标签: swift swift4

我刚转换为Swift 4,现在收到以下错误: 无法下标“String.UnicodeScalarView”类型的值,其索引类型为“CountableRange”(又名“CountableRange”)

代码行是:

extension AppInvite.PromoCode {
    fileprivate static func truncate(string: String) -> String {
    let validCharacters = CharacterSet.alphanumerics
    let cleaned = string.unicodeScalars.filter {
        validCharacters.contains(UnicodeScalar(UInt16($0.value))!)
    }

    let range = 0 ..< min(10, cleaned.count)
    let characters = cleaned[range].map(Character.init)
    return String(characters)
  }
}

我该如何纠正?

1 个答案:

答案 0 :(得分:5)

您使用的是CountableRange<Int>但访问必须使用的字符串CountableRange<String.Index>

let range = cleaned.startIndex..<min(cleaned.index(cleaned.startIndex, offsetBy: 10), cleaned.endIndex)

这是因为在Swift中,String类型的索引类型String.Index而不是Int