early return from a void-func in Swift?

后端 未结 5 1882
情歌与酒
情歌与酒 2020-12-31 07:43

Can someone explain me the following behaviour in Swift?

func test() -> Bool {
    print(\"1 before return\")
    return false
    print(\"1 after return\         


        
5条回答
  •  余生分开走
    2020-12-31 08:04

    Answer extracted from question:

    It seems the problem is, that swift does not exit the function instantly on a return statement in a void function and uses the consecutive void value as the function parameter and terminates as expected if it is non-void.

    Code after 'return' will never be executed

    [...]
    return; // <- would return here
    
    [...]
    return () // <- would return here
    
    [...]
    return // <- would return here
    let x = 42
    

    If Xcode would work reliably this message should be shown on the next examples:

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

    [...]
    return
    print("oh no") // <- would return here
    
    [...]
    return
    myClosure("this feels wrong") // <- would return here and execute the function / closure
    

    This issue is already in the Swift-bug-tracker since 2016: https://bugs.swift.org/browse/SR-2028

提交回复
热议问题