How replace position++ code to make it Swift 3 compatible?

前端 未结 2 1713
感动是毒
感动是毒 2020-12-11 11:36

I have following class, which has method getNextToken to iterate array items:

class Parser {
    let tokens: [Token]
    var position = 0

    i         


        
相关标签:
2条回答
  • 2020-12-11 12:02

    One way is to assign the token to a let constant before incrementing position:

    func getNextToken() -> Token? {
        guard position < tokens.count else {
            return nil
        }
        let token = tokens[position]
        position += 1
        return token
    }
    

    Another way is to save off the current value of position:

    func getNextToken() -> Token? {
        guard position < tokens.count else {
            return nil
        }
        let current = position
        position += 1
        return tokens[current]
    }
    

    Or you could undo the increment:

    func getNextToken() -> Token? {
        guard position < tokens.count else {
            return nil
        }
        position += 1
        return tokens[position - 1]
    }
    
    0 讨论(0)
  • 2020-12-11 12:06

    defer can be used to increment the position variable after the return value has been computed:

    func getNextToken() -> Token? {
        guard position < tokens.count else {
            return nil
        }
        defer {
            position += 1
        }
        return tokens[position]
    }
    
    0 讨论(0)
提交回复
热议问题