What's the most idiomatic way to do some time?
Here is a piece of code I have in the fast-paced Tic Tac Toe project.
var inputTuple = readPositionsFromUser() while inputTuple == nil { print() print("Pay attention!") print() sleep(1) inputTuple = readPositionsFromUser() } let (row, col) = inputTuple!
ReadPositionsFromUser()
prompts the user for a row and column and returns nil if he cannot parse exactly two Ints
, and those Ints
are within the Tic Tac Toe board.
I'm wondering if there is a more idiomatic way to do this, since it !
seems unnecessary on the last line; if this point of code has been reached then I know that InputTuple is non-zero, so the use !
seems silly.
EDIT: I feel like I should clarify that this is a cross-platform command line application. I don't use Cocoa or anything like that.
source to share
The Swift compiler may well be smart enough (when optimizing a release build) to recognize that inputTuple
there cannot be nil in the last statement.
But if you want to eliminate it anyway, you can wrap the loop in a function that returns an optional tuple. You can even use inline closure like:
let (row, col): (Int, Int) = {
while true {
if let inputTuple = readPositionsFromUser() { return inputTuple }
print("\nPay attention!\n")
sleep(1)
}
}()
print("row=\(row) col=\(col)")
source to share