在 Swift 中如何定义函数、定义可选参数、可变参数和函数类型

开发 前端
本文我们介绍了在 Swift 中如何定义函数、定义可选参数、可变参数和函数类型等相关的内容。通过与 TypeScript 语法的对比,希望能帮助您更好地理解 Swift 的相关特性。

本文我们将介绍在 Swift 中如何定义函数、定义可选参数、可变参数和函数类型。

接下来,我们启动 Xcode,然后选择 "File" > "New" > "Playground"。创建一个新的 Playground 并命名为 "Functions"。

在 Swift 中,函数是一种用于执行特定任务的独立代码块。函数使得代码模块化,可重用,并且更易于理解。

定义和调用函数

在 Swift 中,定义函数使用 func 关键字,可以指定参数和返回类型。而在 TypeScript 中,定义函数是使用 function 关键字。

Swift Code

func greet(name: String) -> String {
    return "Hello, \(name)!"
}

let greetingMessage = greet(name: "Semlinker")
print(greetingMessage)

// Output: Hello, Semlinker!

TypeScript Code

function greet(name: string): string {
    return `Hello, ${name}!`;
}

const greetingMessage: string = greet("Semlinker");
console.log(greetingMessage);

// Output: "Hello, Semlinker!"

定义包含多个参数的函数

在定义函数时,可以为函数添加多个参数。

Swift Code

func calculateRectangleArea(length: Double, width: Double) -> Double {
    return length * width
}

let area = calculateRectangleArea(length: 5.0, width: 3.0)
print("The area of the rectangle is \(area)")

// Output: The area of the rectangle is 15.0

TypeScript Code

function calculateRectangleArea(length: number, width: number): number {
    return length * width;
}

const area: number = calculateRectangleArea(5.0, 3.0);
console.log(`The area of the rectangle is ${area}`);

// Output: "The area of the rectangle is 15"

为函数的参数设置默认值

在 Swift 中,可以为函数参数设置默认值。当用户调用函数时,如果未传递参数值,则会使用该参数的默认值。

Swift Code

func greet(name: String, greeting: String = "Hello") -> String {
    return "\(greeting), \(name)!"
}

let customGreeting = greet(name: "Semlinker", greeting: "Greetings")
let defaultGreeting = greet(name: "Semlinker")
print(customGreeting)
print(defaultGreeting)

/**
Output:
Greetings, Semlinker!
Hello, Semlinker!
*/

TypeScript Code

function greet(name: string, greeting: string = "Hello"): string {
    return `${greeting}, ${name}!`;
}

const customGreeting: string = greet("Semlinker", "Greetings");
const defaultGreeting: string = greet("Semlinker");

console.log(customGreeting);
console.log(defaultGreeting);

/**
Output:
"Greetings, Semlinker!"
"Hello, Semlinker!"
*/

定义可选参数

Swift Code

func greet(name: String, greeting: String? = nil) -> String {
    if let customGreeting = greeting {
        return "\(customGreeting), \(name)!"
    } else {
        return "Hello, \(name)!"
    }
}

let customGreeting = greet(name: "Semlinker", greeting: "Greetings")
let defaultGreeting = greet(name: "Semlinker")
print(customGreeting)
print(defaultGreeting)

/**
Output:
Greetings, Semlinker!
Hello, Semlinker!
*/

如果你对 if let 语法不熟悉的话,可以阅读这篇文章。

TypeScript Code

function greet(name: string, greeting?: string): string {
    if (greeting) {
        return `${greeting}, ${name}!`;
    } else {
        return `Hello, ${name}!`;
    }
}

const customGreeting: string = greet("Semlinker", "Greetings");
const defaultGreeting: string = greet("Semlinker");
console.log(customGreeting);
console.log(defaultGreeting);

/**
Output:
"Greetings, Semlinker!"
"Hello, Semlinker!"
*/

定义可变参数

可变参数允许函数接受不定数量的参数。在 Swift 中,通过在参数类型后面添加省略号 ... 来声明可变参数。

Swift Code

func calculateSum(_ numbers: Double...) -> Double {
    return numbers.reduce(0, +)
}

let sum = calculateSum(4, 5, 6)
print("Sum: \(sum)")

// Output: Sum: 15.0

函数 calculateSum 接受一个可变参数 numbers,这意味着它可以接受不定数量的 Double 参数。而下划线 _ 表示我们在调用函数时可以省略对这个参数的外部命名,使调用更加简洁。

Swift Code

let sum1 = calculateSum(4, 5, 6)

在这个调用中,我们直接将数字传递给 calculateSum,而不需要指定参数名。如果没有使用下划线 _,调用将会是这样的:

Swift Code

func calculateSum(numbers: Double...) -> Double {
    return numbers.reduce(0, +)
}

let sum = calculateSum(numbers: 4, 5, 6)

TypeScript Code

function calculateSum(...numbers: number[]): number {
    return numbers.reduce((sum, num) => sum + num, 0);
}

const sum = calculateSum(4, 5, 6);
console.log(`Sum: ${sum}`);

// Output: "Sum: 15"

In-out 参数

在 Swift 中,函数参数可以被声明为 in-out 参数,这意味着这些参数可以被函数改变,并且这些改变会在函数调用结束后保留。这种特性在需要在函数内修改参数值的情况下非常有用。

Swift Code

// Update the quantity of a certain item in the shopping cart
func updateCart(_ cart: inout [String: Int], forProduct product: String, quantity: Int) {
    // If the product already exists, update the quantity;
    // otherwise, add a new product
    if let existingQuantity = cart[product] {
        cart[product] = existingQuantity + quantity
    } else {
        cart[product] = quantity
    }
}

// Initialize shopping cart
var shoppingCart = ["Apple": 3, "Banana": 2, "Orange": 1]

print("Before Update: \(shoppingCart)")

// Call the function and pass in-out parameters
updateCart(&shoppingCart, forProduct: "Banana", quantity: 3)

print("After Update: \(shoppingCart)")

/**
Output: 
Before Update: ["Apple": 3, "Banana": 2, "Orange": 1]
After Update: ["Apple": 3, "Banana": 5, "Orange": 1]
*/

如果将 cart 参数中的 inout 关键字去掉,Swift 编译器会提示以下错误信息:

函数返回多个值

Swift 中的函数可以返回多个值,实际上是返回一个包含多个值的元组。

Swift Code

func getPersonInfo() -> (name: String, age: Int) {
    return ("Semlinker", 30)
}

let personInfo = getPersonInfo()
print("Name: \(personInfo.name), Age: \(personInfo.age)")

// Output: Name: Semlinker, Age: 30

TypeScript Code

function getPersonInfo(): [string, number] {
    return ["Semlinker", 30];
}

const personInfo: [string, number] = getPersonInfo();
console.log(`Name: ${personInfo[0]}, Age: ${personInfo[1]}`);

// Output: "Name: Semlinker, Age: 30"

函数类型

在 Swift 中,函数类型可以用来声明变量、常量、作为函数参数和函数返回值的类型。

声明函数类型

在 Swift 中,声明函数类型时需要指定参数类型和返回类型。

Swift Code

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

// 声明一个函数类型的变量
var mathFunction: (Int, Int) -> Int

// 将 add 函数赋值给变量
mathFunction = add

// 使用函数类型的变量调用函数
let result = mathFunction(2, 3)
print("Result: \(result)")

// Output: Result: 5

TypeScript Code

function add(a: number, b: number): number {
    return a + b;
}

// 声明一个函数类型的变量
let mathFunction: (a: number, b: number) => number;

// 将 add 函数赋值给变量
mathFunction = add;

// 使用函数类型的变量调用函数
const result: number = mathFunction(2, 3);
console.log(`Result: ${result}`);

// Output: "Result: 5"

函数类型作为参数的类型

Swift Code

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

func executeMathOperation(_ a: Int, _ b: Int, _ operation: (Int, Int) -> Int) -> Int {
    return operation(a, b)
}

// 调用以上函数并将 add 函数作为参数传递
let result = executeMathOperation(2, 3, add)

print("Result: \(result)")

// Output: Result: 5

TypeScript Code

function add(a: number, b: number): number {
    return a + b;
}

function executeMathOperation(a: number, b: number, operation: (a: number, b: number) => number): number {
    return operation(a, b);
}

// 调用以上函数并将 add 函数作为参数传递
const result = executeMathOperation(2, 3, add);
console.log(`Result: ${result}`);

// Output: "Result: 5"

函数类型作为返回值的类型

Swift Code

func add(_ a: Int, _ b: Int) -> Int {
    return a + b
}

// 定义一个返回加法函数的函数
func getAdditionFunction() -> (Int, Int) -> Int {
    return add
}

// 获取加法函数并调用
let additionFunction = getAdditionFunction()
let result = additionFunction(2, 3)
print("Result: \(result)")

// Output: Result: 5

TypeScript Code

function add(a: number, b: number): number {
    return a + b;
}

// 定义一个返回加法函数的函数
function getAdditionFunction(): (a: number, b: number) => number {
    return add;
}

// 获取加法函数并调用
const additionFunction: (a: number, b: number) => number = getAdditionFunction();
const result: number = additionFunction(2, 3);
console.log(`Result: ${result}`);

// Output: "Result: 5"

本文我们介绍了在 Swift 中如何定义函数、定义可选参数、可变参数和函数类型等相关的内容。通过与 TypeScript 语法的对比,希望能帮助您更好地理解 Swift 的相关特性。

责任编辑:姜华 来源: 全栈修仙之路
相关推荐

2011-08-01 17:11:43

Objective-C 函数

2022-11-06 21:50:59

Python编程函数定义

2024-01-16 07:33:02

SwiftTypeScript可选绑定

2010-10-08 09:37:31

JavaScript函

2009-07-22 07:53:00

Scala无参数方法

2021-03-27 10:54:34

Python函数代码

2018-08-27 14:50:46

LinuxShellBash

2023-10-31 09:10:39

2010-11-08 14:47:02

Powershell函数

2021-03-16 10:39:29

SpringBoot参数解析器

2010-01-28 10:49:22

C++构造函数

2010-02-02 18:14:38

Python函数

2009-10-16 13:08:40

VB自定义类型参数

2009-12-07 19:34:01

PHP函数可变参数列表

2009-06-29 15:23:00

2022-11-07 09:02:13

Python编程位置

2023-11-01 08:01:04

SpringWeb容器

2010-07-26 13:13:33

Perl函数参数

2019-12-02 21:29:45

Keras神经网络TensorFlow

2009-07-21 17:21:57

Scala定义函数
点赞
收藏

51CTO技术栈公众号