swift - 为什么函数不被视为命名类型?

标签 swift types named

这直接来自 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是“一个接受 DoubleDouble 并返回 Bool 的函数”,而第二个函数 one 的类型是“一个接受 Double 并返回 Bool 的函数”。

下面是两个相同类型但名称不同的函数的示例:

func one(x: Double) -> Bool {
    return true
}
func two(x: Double) -> Bool {
    return false
}

这两个函数的复合类型是“接受 Double 并返回 Bool 的函数”。两个功能onetwo是该复合类型的实例

关于swift - 为什么函数不被视为命名类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880594/

相关文章:

dart - 如果未提供dart可选的named参数,为什么不为null?

swift - Firestore 查询 Swift 4.0 缺少返回

ios - 当单元格插入表格时,自定义表格 View 单元格内的 ImageView 消失

ios - SpriteKit : detect overlap of rotated nodes?

types - SML 算术函数的类型被推断为 int

c - 指针分配二维数组指针的警告消息

c++ - 哪些右值有名字?

Swift:总是从 Firebase 获取最新的项目

python - 有没有办法在重新索引/上采样时间序列时防止 dtype 从 Int64 更改为 float64?

lambda - Kotlin:命名 lambda 参数的用途是什么?