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

Why are functions not considered as named type?

这直接来自 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.

函数也有名字,为什么函数被认为是复合类型而不是命名类型?

函数不是类型,这就是为什么函数不被视为复合类型的原因。这也是函数不在该列表中的原因。

类型有类、枚举等。函数接近于语言,而 类 等是 object-oriented 工作方式。

函数既有名称又有类型。函数的名称单独表示该函数的 name;它不表示该函数的类型

其实函数的名称和类型是相互独立的:

  • 多个同名函数允许不同类型,并且
  • 允许具有相同类型的多个函数具有不同的名称。

下面是两个同名不同类型函数的例子:

func one(x: Double, y: Double) -> Bool {
    return true
}
func one(x: Double) -> Bool {
    return true
}

第一个函数one的复合类型是"a function taking a Double and a Double, and returning a Bool",而第二个函数one的类型是"a function taking a Double and returning a Bool"。

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

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

两个函数的复合类型都是"a function taking a Double and returning a Bool"。函数 onetwo 都是该复合类型的 实例