为什么我不能直接在函数中返回Void

LK *_*ung 9 return function void swift

在test1()中,它可以返回test()成功返回的Void.但在test2()中,错误抛出.为什么?

//: Playground - noun: a place where people can play

import UIKit
import AVFoundation

func test()->Void{
    print("Hello")
}

func test1(){//print Hello
    return test()
}

func test2(){// throw error
    return Void
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*res 14

Void是一种类型,因此无法返回.相反,你想要返回Void的表示,这是一个空元组.

因此,请尝试这样做,这将编译:

func test()->Void{
    print("Hello")
}

func test1(){//print Hello
    return test()
}

func test2()->Void{// throw error
    return ()
}

test1()
Run Code Online (Sandbox Code Playgroud)

有关为什么可以在希望返回Void类型的函数中返回空的tupple的更多信息,请在以下链接中搜索void:https: //developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language /Functions.html