0

我有一个逐字符的函数,可以从文件中返回一个字符。就我现在而言,它的性能非常好。

Xcode 表示characterPointer.initialize(from: s.characters)“将在 Swift 4.0 中删除”。而且我必须“改用'UnsafeMutableBufferPointer.initialize(from:)'”。

但我无法得到它。你能给我解释一下吗?如何在带有 UnsafeMutableBufferPointer 的字符上使用快速迭代器?你有一个例子吗?

这是我的功能:

/// Return next character, or nil on EOF.
func nextChar() -> Character? {
    //precondition(fileHandle != nil, "Attempt to read from closed file")

    if atEof {
        return nil
    }

    if stored_cnt > (stored_idx + 1) {
        stored_idx += 1
        let char = characterPointer.pointee
        characterPointer = characterPointer.successor()
        return char
    }

    let tmpData = fileHandle.readData(ofLength: (chunkSize))
    if tmpData.count == 0 {
        atEof = true
        return nil
    }

    if var s = NSString(data: tmpData, encoding: encoding.rawValue) as String! {
        characterPointer.initialize(from: s.characters)

        stored_idx = 0
        stored_cnt = s.characters.count
    }
    let char = characterPointer.pointee
    characterPointer = characterPointer.successor()
    return char
}

顺便说一句,如果有更快的解决方案,请不要犹豫告诉我。

非常感谢。

4

0 回答 0