early return from a void-func in Swift?

后端 未结 5 1877
情歌与酒
情歌与酒 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:00

    It is a tricky thing, Swift doesn't require semi-colons (they are optionally used), this makes Swift compiler automatically deduce whether is the next line should be a new line, or a completion for the old one. print() is a function that returns void. So the word return print("something"), is valid. So

    return
    print("Something")
    

    could be deduced as return print("Something")

    Your solution is to write

    return;
    print("Something")
    

提交回复
热议问题