Swift 4 中到 FileHandle 指针和字符编码的索引距离

Index distance to FileHandle pointer and characters encoding in Swift 4

我有这个功能return(并寻找)一个特定单词的 FileHandle 指针:

func getFilePointerIndex(atWord word: String, inFile file: FileHandle) -> UInt64? {
    let offset = file.offsetInFile
    if let str = String(data: file.readDataToEndOfFile(), encoding: .utf8) {
        if let range = str.range(of: word) {
            let intIndex = str.distance(from: str.startIndex, to: range.lowerBound)
            file.seek(toFileOffset: offset + UInt64(intIndex))
            return UInt64(intIndex) + offset
        }
    }
    return nil
}

当应用于一些 utf8 文本文件时,它产生的偏移结果远离传入单词的位置。我认为它必须是字符编码(可变字节字符),因为 seek(toFileOffset:)方法适用于 class 个数据对象。

有解决办法吗?

let intIndex = str.distance(from: str.startIndex, to: range.lowerBound)

测量 Characters 中的距离,即“扩展 Unicode 字素 集群”。例如,字符“€”将存储为三个 UTF-8 编码的字节“0xE2 0x82 0xAC”,但算作一个 Character.

要以 UTF-8 代码单位测量距离,请使用

let intIndex = str.utf8.distance(from: str.utf8.startIndex, to: range.lowerBound)

另请参阅 Swift 博客中的 Strings in Swift 2,了解有关字素簇和 Swift 字符串的不同视图。