Swift 函数重载
在本教程中,我们将通过示例了解 Swift 中的函数重载。
在 Swift 中,如果两个或多个函数的参数不同(参数数量不同、参数类型不同或两者都不同),则它们可能具有相同的名称。
这些函数称为重载函数,此特性称为函数重载。例如:
// same function name different argumentsfunc test() { ... }func test(value: Int) -> Int{ ... }func test(value: String) -> String{ ... }func test(value1: Int, value2: Double) -> Double{ ... }
这里,test() 函数被重载。这些函数具有相同的名称,但接受不同的参数。
注意:以上函数的返回类型不同。这是因为函数重载与返回类型无关。重载函数可能具有相同或不同的返回类型,但它们的参数必须不同。
实例 1:不同参数类型的重载
// function with Int type parameterfunc displayValue(value: Int) {print("Integer value:", value)}// function with String type parameterfunc displayValue(value: String) {print("String value:", value)}// function call with String type parameterdisplayValue(value: "Swift")// function call with Int type parameterdisplayValue(value: 2)
结果为:
String value: SwiftInteger value: 2
在上面的实例中,我们重载了 displayValue() 函数:
- 一个函数具有 Int 类型参数
- 另一个具有 String 类型参数
根据函数调用期间传递的参数类型,调用相应的函数。

实例 2:不同参数数的重载
// function with two parametersfunc display(number1: Int, number2: Int) {print("1st Integer: \(number1) and 2nd Integer: \(number2)")}// function with a single parameterfunc display(number: Int) {print("Integer number: \(number)")}// function call with single parameterdisplay(number: 5)// function call with two parametersdisplay(number1: 6, number2: 8)
结果如下:
Integer number: 51st Integer: 6 and 2nd Integer: 8
实例 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: 25Person2 Age: 38
在上面的示例中,两个同名的函数 display() 具有相同的数量和相同的参数类型。然而,我们仍然能够重载该函数。
这是因为,在 Swift 中,我们还可以使用参数标签重载函数。
这里,两个函数有不同的 参数标签。并且,根据函数调用期间使用的参数标签,调用相应的函数。