[Xcode / Swift5] Note "Expression following'return' is treated as an argument of the'return'", which is executed unintentionally after the return.

The development environment is Xcode 12.1.

During debugging, something may cause a return in the middle of the process.

func hoge(){
    print("A")
    return
    print("B")
    print("C")
}

Naturally print ("A") is executed. So, shockingly, print ("B ") is ** executed **.

why? ?? ?? ?? ?? ??

I ran into a similar situation in more complex code and worried about 20 minutes. However, there is actually a warning. Due to the complicated nested code, the warning was not displayed in full, and I didn't read it thinking, "Of course, it says code after'return'will never be executed. " , This was a big deal.

Expression following 'return' is treated as an argument of the 'return'

In other words, the next part of return is interpreted as the return value. Indeed, print ("B ") returns Void. The return value of the function hoge is also Void. So the interpretation is correct. In other words, the code at the beginning is interpreted as follows.

func hoge() -> Void {
    print("A")
    return print("B")
    print("C")
}

That's why print ("B ") is called. I didn't write the code with that in mind ...

I read the warning without ignoring it, and I felt like commenting out obediently without writing return in strange places.

Recommended Posts

[Xcode / Swift5] Note "Expression following'return' is treated as an argument of the'return'", which is executed unintentionally after the return.
Which is faster, size or 0, as the argument of List # toArray?