early return from a void-func in Swift?

后端 未结 5 1870
情歌与酒
情歌与酒 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 07:53

    func test2() is similar to func test2() -> Void

    So your code gets treated as,

    func test2() -> Void {
      print("2 before return")
      return print("2 after return")
    }
    

    Adding semicolon after print should fix it.

    func test2() -> Void {
      print("2 before return")
      return; print("2 after return")
    }
    

    You can also see the error if you place value type after return line and you will understand more,

    func test2() {
      print("2 before return")
      return
      2
    }
    

    error: unexpected non-void return value in void function 2 ^

提交回复
热议问题