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

前端 未结 2 1723
感动是毒
感动是毒 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]
    }
    

提交回复
热议问题