成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

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

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

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

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

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

定義和調(diào)用函數(shù)

在 Swift 中,定義函數(shù)使用 func 關(guān)鍵字,可以指定參數(shù)和返回類型。而在 TypeScript 中,定義函數(shù)是使用 function 關(guān)鍵字。

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!"

定義包含多個參數(shù)的函數(shù)

在定義函數(shù)時,可以為函數(shù)添加多個參數(shù)。

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"

為函數(shù)的參數(shù)設(shè)置默認值

在 Swift 中,可以為函數(shù)參數(shù)設(shè)置默認值。當(dāng)用戶調(diào)用函數(shù)時,如果未傳遞參數(shù)值,則會使用該參數(shù)的默認值。

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!"
*/

定義可選參數(shù)

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!"
*/

定義可變參數(shù)

可變參數(shù)允許函數(shù)接受不定數(shù)量的參數(shù)。在 Swift 中,通過在參數(shù)類型后面添加省略號 ... 來聲明可變參數(shù)。

Swift Code

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

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

// Output: Sum: 15.0

函數(shù) calculateSum 接受一個可變參數(shù) numbers,這意味著它可以接受不定數(shù)量的 Double 參數(shù)。而下劃線 _ 表示我們在調(diào)用函數(shù)時可以省略對這個參數(shù)的外部命名,使調(diào)用更加簡潔。

Swift Code

let sum1 = calculateSum(4, 5, 6)

在這個調(diào)用中,我們直接將數(shù)字傳遞給 calculateSum,而不需要指定參數(shù)名。如果沒有使用下劃線 _,調(diào)用將會是這樣的:

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 參數(shù)

在 Swift 中,函數(shù)參數(shù)可以被聲明為 in-out 參數(shù),這意味著這些參數(shù)可以被函數(shù)改變,并且這些改變會在函數(shù)調(diào)用結(jié)束后保留。這種特性在需要在函數(shù)內(nèi)修改參數(shù)值的情況下非常有用。

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 參數(shù)中的 inout 關(guān)鍵字去掉,Swift 編譯器會提示以下錯誤信息:

函數(shù)返回多個值

Swift 中的函數(shù)可以返回多個值,實際上是返回一個包含多個值的元組。

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"

函數(shù)類型

在 Swift 中,函數(shù)類型可以用來聲明變量、常量、作為函數(shù)參數(shù)和函數(shù)返回值的類型。

聲明函數(shù)類型

在 Swift 中,聲明函數(shù)類型時需要指定參數(shù)類型和返回類型。

Swift Code

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

// 聲明一個函數(shù)類型的變量
var mathFunction: (Int, Int) -> Int

// 將 add 函數(shù)賦值給變量
mathFunction = add

// 使用函數(shù)類型的變量調(diào)用函數(shù)
let result = mathFunction(2, 3)
print("Result: \(result)")

// Output: Result: 5

TypeScript Code

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

// 聲明一個函數(shù)類型的變量
let mathFunction: (a: number, b: number) => number;

// 將 add 函數(shù)賦值給變量
mathFunction = add;

// 使用函數(shù)類型的變量調(diào)用函數(shù)
const result: number = mathFunction(2, 3);
console.log(`Result: ${result}`);

// Output: "Result: 5"

函數(shù)類型作為參數(shù)的類型

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)
}

// 調(diào)用以上函數(shù)并將 add 函數(shù)作為參數(shù)傳遞
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);
}

// 調(diào)用以上函數(shù)并將 add 函數(shù)作為參數(shù)傳遞
const result = executeMathOperation(2, 3, add);
console.log(`Result: ${result}`);

// Output: "Result: 5"

函數(shù)類型作為返回值的類型

Swift Code

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

// 定義一個返回加法函數(shù)的函數(shù)
func getAdditionFunction() -> (Int, Int) -> Int {
    return add
}

// 獲取加法函數(shù)并調(diào)用
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;
}

// 定義一個返回加法函數(shù)的函數(shù)
function getAdditionFunction(): (a: number, b: number) => number {
    return add;
}

// 獲取加法函數(shù)并調(diào)用
const additionFunction: (a: number, b: number) => number = getAdditionFunction();
const result: number = additionFunction(2, 3);
console.log(`Result: ${result}`);

// Output: "Result: 5"

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

責(zé)任編輯:姜華 來源: 全棧修仙之路
相關(guān)推薦

2011-08-01 17:11:43

Objective-C 函數(shù)

2024-01-16 07:33:02

SwiftTypeScript可選綁定

2022-11-06 21:50:59

Python編程函數(shù)定義

2010-10-08 09:37:31

JavaScript函

2009-07-22 07:53:00

Scala無參數(shù)方法

2025-01-17 10:52:26

定義函數(shù)編程Python

2021-03-27 10:54:34

Python函數(shù)代碼

2025-02-12 10:51:51

2024-09-19 20:59:49

2018-08-27 14:50:46

LinuxShellBash

2023-10-31 09:10:39

2010-11-08 14:47:02

Powershell函數(shù)

2010-01-28 10:49:22

C++構(gòu)造函數(shù)

2009-12-07 19:34:01

PHP函數(shù)可變參數(shù)列表

2025-04-02 12:00:00

開發(fā)日志記錄Python

2010-02-02 18:14:38

Python函數(shù)

2009-06-29 15:23:00

2021-03-16 10:39:29

SpringBoot參數(shù)解析器

2009-10-16 13:08:40

VB自定義類型參數(shù)

2022-11-07 09:02:13

Python編程位置
點贊
收藏

51CTO技術(shù)棧公眾號

主站蜘蛛池模板: 夜夜爽99久久国产综合精品女不卡 | 久久久高清 | 国产精品91视频 | www.国产.com | 亚洲综合国产 | av日日操 | 国产精品色| 一级片子| 国产精品一卡二卡三卡 | 亚洲欧美日韩久久久 | 成人精品一区亚洲午夜久久久 | 免费特级黄毛片 | 激情欧美日韩一区二区 | 国产午夜视频 | 久在线视频播放免费视频 | 91精品久久久久久久久中文字幕 | 日韩三级 | 国产精品自拍视频网站 | 国产一级片在线观看视频 | 91网站视频在线观看 | 国产一级片在线播放 | 久久精品aaa| 久久av一区二区 | 欧洲成人 | 国产精品1区2区3区 欧美 中文字幕 | 国产精品亚洲视频 | 亚洲精品国产第一综合99久久 | 国产美女特级嫩嫩嫩bbb片 | 久久成人免费 | 国产精品日韩在线观看 | 精品视频久久久久久 | www.欧美视频| 91亚洲欧美 | 天天操网 | 亚洲精品久久久蜜桃网站 | 久久精品一区二区三区四区 | 三级成人在线 | 亚洲国产精品网站 | 中国一级大毛片 | 日韩成人在线电影 | 国内自拍偷拍视频 |