迁移到Swift 3的麻烦:String.CharacterView对应'startIndex'

时间:2016-09-28 04:56:21

标签: ios swift xcode collections

代码:

let startIndex = oldString.characters.index(oldString.startIndex, offsetBy: range.location)

let endIndex = String.Characterview corresponding to 'startIndex' .index(startIndex, offsetBy: 5)

在迁移到Swift 3之前,上面一行是:

let endIndex = startIndex.advancedBy(5)

我知道文档说advancedBy应该转换为:

Collection.index(index, offsetBy: delta)

但是当我执行上面的代码时,我收到了这个错误:

  

协议集合只能用作通用约束,因为它具有自我或相关类型要求

问题:

那么我需要在这做什么呢?我觉得这很简单,我只是大麦错过了它。我一直在博客和互联网上。

1 个答案:

答案 0 :(得分:0)

通常,您可以使用以下方法获取String.Index

  • startIndex
  • endIndex
  • index(before: String.Index)
  • index(after: String.Index)
  • index(i: String.Index, offsetBy: String.IndexDistance)
  • index(i: String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

然后您可以像往常一样使用String.substring

let testStr = "1234567890abcdefghij"

//string length
let testStrLengh = testStr.characters.count

//get tail 10 characters
let tail1 = testStr[testStr.index(testStr.endIndex, offsetBy: -10)..<testStr.endIndex]
let tail2 = testStr.substring(from: testStr.index(testStr.endIndex, offsetBy: -10))

//get head 10 characters
let head1 = testStr[testStr.startIndex..<testStr.index(testStr.startIndex, offsetBy: 10)]
let head2 = testStr.substring(to: testStr.index(testStr.startIndex, offsetBy: 10))

//get centre 10 characters
let startIndex = testStr.index(testStr.startIndex, offsetBy: 5)
let endIndex = testStr.index(testStr.endIndex, offsetBy: -5)
let centreStr = testStr.substring(with: startIndex..<endIndex)