到文件句柄指针的索引距离和Swift 4中的字符编码

到文件句柄指针的索引距离和Swift 4中的字符编码,swift,character-encoding,filehandle,file-pointer,Swift,Character Encoding,Filehandle,File Pointer,我使用此函数返回(并查找)特定单词的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 rang

我使用此函数返回(并查找)特定单词的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:)方法适用于类数据对象

有什么好办法吗

let intIndex = str.distance(from: str.startIndex, to: range.lowerBound)
测量
字符
s中的距离,即“扩展Unicode字符集” 集群”。例如,字符“€”将存储为三个字符 UTF-8编码中的字节“0xE2 0x82 0xAC”,但计为单个字节
字符

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

let intIndex = str.utf8.distance(from: str.utf8.startIndex, to: range.lowerBound)
另请参见Swift博客中有关grapheme集群和 快捷字符串的不同视图