如何将 Int 转换为 String.CharacterView.Index

How to convert Int to String.CharacterView.Index

这让我抓狂。

在Swift 2.2 中,String 无法用Int 下标。例如:

let myString = "Test string"
let index = 0
let firstCharacter = myString[index]

这将导致编译错误,显示

'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion

我看到的一个解决方法是将整数转换为索引类型,但我不知道如何..

并不是说下标就一定不行,只是多了一步就可以得到和以前一样的结果。下面,我和你做了同样的事情,但是在 Swift 2.2

let myString = "Test string"
let intForIndex = 0
let index = myString.startIndex.advancedBy(intForIndex)
let firstCharacter = myString[index]

Swift 3.x + 4.x

let myString = "Test string"
let intForIndex = 0
let index = myString.index(myString.startIndex, offsetBy: intForIndex)
let firstCharacter = myString[index]

编辑 1:

更新了代码,以便您可以在其他地方使用传递到 "index" 值的 Int


语法编辑:

我会持续更新此答案以支持最新版本的 Swift。

这也让我很恼火,所以我写了一个扩展来处理它:

extension String {
    subscript (index: Int) -> Character {
        let charIndex = self.startIndex.advancedBy(index)
        return self[charIndex]
    }

    subscript (range: Range<Int>) -> String {
        let startIndex = self.startIndex.advancedBy(range.startIndex)
        let endIndex = startIndex.advancedBy(range.count)

        return self[startIndex..<endIndex]
    }
}

// Usage
let str = "Hello world"

print(str[0])       // H
print(str[0..<5])   // Hello

更新 Swift 4.x:

extension String {
    subscript (index: Int) -> Character {
        let charIndex = self.index(self.startIndex, offsetBy: index)
        return self[charIndex]
    }

    subscript (range: Range<Int>) -> Substring {
        let startIndex = self.index(self.startIndex, offsetBy: range.startIndex)
        let stopIndex = self.index(self.startIndex, offsetBy: range.startIndex + range.count)
        return self[startIndex..<stopIndex]
    }

}

let s = "‍‍‍ family"

print(s[0])      // ‍‍‍
print(s[2..<8])  // family

ZGski 答案已更新为 Swift 3

let testText = "Test text 123"  
let position = 11  
let index = testText.characters.index(testText.startIndex, offsetBy: position)  
let character = testText[index] // "2"

swift 4 的示例:

let myString = "Test string"
let index = 0
let firstCharacter = myString[String.Index(encodedOffset: index)]

一个简单的作弊方法是将字符串转换为字符数组,您可以使用 Int 对其进行索引:

let a = Array("hello")
for i in a.indices {
   print(a[i])
}