自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

在 Swift 中如何定義函數、定義可選參數、可變參數和函數類型

開發(fā) 前端
本文我們介紹了在 Swift 中如何定義函數、定義可選參數、可變參數和函數類型等相關的內容。通過與 TypeScript 語法的對比,希望能幫助您更好地理解 Swift 的相關特性。

本文我們將介紹在 Swift 中如何定義函數、定義可選參數、可變參數和函數類型。

接下來,我們啟動 Xcode,然后選擇 "File" > "New" > "Playground"。創(chuàng)建一個新的 Playground 并命名為 "Functions"。

在 Swift 中,函數是一種用于執(zhí)行特定任務的獨立代碼塊。函數使得代碼模塊化,可重用,并且更易于理解。

定義和調用函數

在 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可選綁定

2009-07-22 07:53:00

Scala無參數方法

2025-01-17 10:52:26

定義函數編程Python

2010-10-08 09:37:31

JavaScript函

2021-03-27 10:54:34

Python函數代碼

2025-02-12 10:51:51

2024-09-19 20:59:49

2023-10-31 09:10:39

2018-08-27 14:50:46

LinuxShellBash

2010-11-08 14:47:02

Powershell函數

2010-02-02 18:14:38

Python函數

2025-04-02 12:00:00

開發(fā)日志記錄Python

2009-12-07 19:34:01

PHP函數可變參數列表

2021-03-16 10:39:29

SpringBoot參數解析器

2009-06-29 15:23:00

2022-11-07 09:02:13

Python編程位置

2010-07-26 13:13:33

Perl函數參數

2010-01-28 10:49:22

C++構造函數
點贊
收藏

51CTO技術棧公眾號