I have following class, which has method getNextToken
to iterate array items:
class Parser {
let tokens: [Token]
var position = 0
i
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]
}
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]
}