这直接来自 Swift 开发人员指南。
In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it is defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass. In addition to user-defined named types, the Swift standard library defines many commonly used named types, including those that represent arrays, dictionaries, and optional values. .... A compound type is a type without a name, defined in the Swift language itself. There are two compound types: function types and tuple types.
函数也有名称,为什么函数被视为复合类型而不是命名类型?
最佳答案
函数有名称和类型。函数的名称表示该函数本身的名称;它并不表示该函数的类型。
事实上,函数的名称和类型是相互独立的:
- 多个同名函数可以有不同的类型,并且
- 多个具有相同类型的函数可以具有不同的名称。
以下是具有相同名称和不同类型的两个函数的示例:
func one(x: Double, y: Double) -> Bool {
return true
}
func one(x: Double) -> Bool {
return true
}
第一个函数的复合类型one
是“一个接受 Double
和 Double
并返回 Bool
的函数”,而第二个函数 one
的类型是“一个接受 Double
并返回 Bool
的函数”。
下面是两个相同类型但名称不同的函数的示例:
func one(x: Double) -> Bool {
return true
}
func two(x: Double) -> Bool {
return false
}
这两个函数的复合类型是“接受 Double
并返回 Bool
的函数”。两个功能one
和two
是该复合类型的实例。
关于swift - 为什么函数不被视为命名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880594/