I was writing some code and made a mistake that simplifies to:
func f() -> Int {
for _ in [1,2,3] {
return 1
}
}
And the compiler shows me an error saying that f
is missing an return, which caused me to realise my mistake. I forgot to put an if statement around the return
!
But then I realised that the compiler is actually lying! The function will always return a value. Or will it? Is there any situation under which the for loop will not loop?
I'm asking this because other tautological constructs compiles fine:
if 1 < 2 {
return 1
}
while true {
return 1
}
And I also understand that the compiler can't evaluate every expression at compile time to see if they are tautologies. I know properties accesses and method calls usually don't get evaluated at compile time, so this is not expected to compile:
if "".isEmpty {
return 1
}
But generally literals are ok, right? After all, the compiler has to evaluate the literal [1,2,3]
to translate it into machine code that says "create an array with 1, 2, 3".
So why is it not smart enough to figure out the for loop? Will the for loop not get run in some rare situation?