在 Swift 中如何定義函數(shù)、定義可選參數(shù)、可變參數(shù)和函數(shù)類型
本文我們將介紹在 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)特性。