为什么 Swift 的类型检查系统允许 return 类型的函数不 return 任何类型?
Why does Swift's typechecking system allow a function that returns a type to not return anything?
为什么下面的代码有效?
func square(_ x: Int) -> Int {
fatalError()
}
fatalError() 从不 return 任何东西(或者更确切地说,它 return 从不)。为什么类型系统在这里没有发现 func 不是 return Int 的问题,即使它说它会?
考虑 throw
可以概念化为具有 Never 类型。它的工作方式与进一步的代码执行相同,包括潜在的 return,在 throw
完全不合逻辑之后。
func square(_ x: Int) -> Int {
throw TooManyDotsError()
}
在调用类型为 -> Never
的函数时也接受此行为允许 throw
和 fatalError()
之间的相同统一。
Use Never as the return type when declaring a closure, function, or method that unconditionally throws an error [as the throw
statement does], traps, or otherwise does not terminate.
方法的return类型表示如果方法returns,它必须return给定类型的值.调用“从不”方法,与 throw
一样, 排除在给定分支上 returning。
为了展示它的用处,比较没有将它内置到类型系统中的语言,例如 C#:
int F() {
// guaranteed to throw, but not known to type system
AlwaysThrow();
// dummy throw to appease type system
throw Exception("Not reachable");
}
因为fatalError
returns Never
。从文档中,Never
是,
The return type of functions that do not return normally, that is, a type with no values.
通过编译器魔法,Swift 理解 fatalError
“通常不会 return”,即它会使应用程序崩溃。这就是为什么它不抱怨 square
而不是 returning 一个 Int
.
如果您的函数路径调用了一个“通常不会 return”的函数,那么该路径也不会 return 通常。 “Does not return normally”意味着调用者将无法使用 return 值,因此在你函数的那个路径。
为什么下面的代码有效?
func square(_ x: Int) -> Int {
fatalError()
}
fatalError() 从不 return 任何东西(或者更确切地说,它 return 从不)。为什么类型系统在这里没有发现 func 不是 return Int 的问题,即使它说它会?
考虑 throw
可以概念化为具有 Never 类型。它的工作方式与进一步的代码执行相同,包括潜在的 return,在 throw
完全不合逻辑之后。
func square(_ x: Int) -> Int {
throw TooManyDotsError()
}
在调用类型为 -> Never
的函数时也接受此行为允许 throw
和 fatalError()
之间的相同统一。
Use Never as the return type when declaring a closure, function, or method that unconditionally throws an error [as the
throw
statement does], traps, or otherwise does not terminate.
方法的return类型表示如果方法returns,它必须return给定类型的值.调用“从不”方法,与 throw
一样, 排除在给定分支上 returning。
为了展示它的用处,比较没有将它内置到类型系统中的语言,例如 C#:
int F() {
// guaranteed to throw, but not known to type system
AlwaysThrow();
// dummy throw to appease type system
throw Exception("Not reachable");
}
因为fatalError
returns Never
。从文档中,Never
是,
The return type of functions that do not return normally, that is, a type with no values.
通过编译器魔法,Swift 理解 fatalError
“通常不会 return”,即它会使应用程序崩溃。这就是为什么它不抱怨 square
而不是 returning 一个 Int
.
如果您的函数路径调用了一个“通常不会 return”的函数,那么该路径也不会 return 通常。 “Does not return normally”意味着调用者将无法使用 return 值,因此在你函数的那个路径。