Is there a way to check a condition for each line of a function without needing to write a sequence of identical statements?
For example, let's say we are passing through a maze of squares, where each square may randomly have a coin to collect, whereas some squares may not have a coin to collect.
Is there an efficient way to write a function that checks each square for a coin, collects a coin if there is a coin, then moves to the designated next square? I only want to run the collectCoin() method if there is a coin. Otherwise, I just want to check if there's a coin and pass through the square if there isn't a coin.
Here's an example of what I perceive to be an inefficient method:
func collectTheCoins() {
if isOnCoin {
collectCoin()
}
moveForward()
if isOnCoin {
collectCoin()
}
moveRight()
if isOnCoin {
collectCoin()
}
moveLeft()
if isOnCoin {
collectCoin()
}
}
For efficiency purposes, my objective is to only run the collectCoin() method if in fact there is a coin to collect.