Preparing for Swift 4 - UnsafeMutablePointer migration to UnsafeMutableBufferPointer

…衆ロ難τιáo~ 提交于 2019-12-08 11:03:02

问题


I've got a char-by-char function that returns a character from a file. It is pretty performant, as far as i now.

Xcode says that the characterPointer.initialize(from: s.characters) "will be removed in Swift 4.0." And I have to "use 'UnsafeMutableBufferPointer.initialize(from:)' instead".

But I can't get it. Can you please explain it to me. How to use a quick iterator over characters with a UnsafeMutableBufferPointer? Do you have an example?

This is my function:

/// 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
}

By the way, if there is a faster solution, please do not hesitate to tell me.

Thanks a lot.

来源:https://stackoverflow.com/questions/43772575/preparing-for-swift-4-unsafemutablepointer-migration-to-unsafemutablebufferpoi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!