Swift 函数重载

在 Swift 中,如果两个或多个函数的参数不同(参数数量不同、参数类型不同,或两者皆有),则它们可以具有相同的名称。

这些函数称为重载函数,这个特性称为函数重载。例如

// same function name different arguments
func test() { ... }
func test(value: Int) -> Int{ ... }
func test(value: String) -> String{ ... }
func test(value1: Int, value2: Double) -> Double{ ... }

这里,test() 函数被重载了。这些函数具有相同的名称,但接受不同的参数。

注意:上述函数的返回类型不一定相同。这是因为函数重载与返回类型无关。重载函数可以具有相同的或不同的返回类型,但它们必须在参数上有所区别。


示例 1:通过不同的参数类型进行重载

// function with Int type parameter
func displayValue(value: Int) {
    print("Integer value:", value)
}

// function with String type parameter
func displayValue(value: String) {
    print("String value:", value)
}

// function call with String type parameter
displayValue(value: "Swift")

// function call with Int type parameter
displayValue(value: 2)

输出

String value: Swift
Integer value: 2

在上面的示例中,我们重载了 displayValue() 函数

  • 一个函数具有 Int 类型的参数
  • 另一个函数具有 String 类型的参数

根据函数调用时传递的参数类型,会调用相应的函数。

Working of Swift Function Overloading for displayValue() function
Swift 函数重载对 displayValue() 函数的工作原理

示例 2:通过不同的参数数量进行重载

// function with two parameters
func display(number1: Int, number2: Int) {
   print("1st Integer: \(number1) and 2nd Integer: \(number2)")
}

// function with a single parameter
func display(number: Int) {
   print("Integer number: \(number)")
}


// function call with single parameter
display(number: 5)

// function call with two parameters
display(number1: 6, number2: 8)

输出

Integer number: 5
1st Integer: 6 and 2nd Integer: 8

在这里,我们使用不同数量的参数重载了 display() 函数。

根据函数调用时传递的参数数量,会调用相应的函数。

Working of Swift Function Overloading for display() function
Swift 函数重载对 display() 函数的工作原理

示例 3:通过参数标签进行函数重载

func display(person1 age:Int) {
    print("Person1 Age:", age)
}

func display(person2 age:Int) {
    print("Person2 Age:", age)
}

display(person1: 25)

display(person2: 38)

输出

Person1 Age: 25
Person2 Age: 38

在上面的示例中,两个同名 display() 的函数具有相同的参数数量和相同的参数类型。但是,我们仍然可以重载该函数。

这是因为,在 Swift 中,我们也可以通过使用参数标签来重载函数。

这里,两个函数具有不同的参数标签。并且,根据函数调用时使用的参数标签,会调用相应的函数。

目录

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战