Swift 函式中返回多個值
在 Swift 中,您可以使用元組從函式返回多個值。在本文中,您將看到使用元組從函式返回多個值的各種示例。以下是一些更實用的使用 Swift 中的元組返回多個值的函式示例:
示例 1 - 將 URL 解析為其組成部分
import Foundation
func parseURL(urlString: String) -> (scheme: String, host: String, path: String) {
guard let url = URL(string: urlString) else {
fatalError("Invalid URL")
}
return (url.scheme ?? "", url.host ?? "", url.path)
}
let components = parseURL(urlString: "https://www.example.com/path/to/resource")
print("Scheme:", components.scheme)
print("Host:", components.host)
print("Path:", components.path)
輸出
Scheme: https Host: www.example.com Path: /path/to/resource
在這個例子中,`parseURL` 函式接受一個表示 URL 的字串,並返回一個包含 URL 的方案、主機和路徑元件的元組。如果 URL 無效,則函式會引發致命錯誤。
示例 2 - 將字串拆分為單詞並計算其出現次數
import Foundation
func countWords(text: String) -> (words: [String], counts: [String: Int]) {
let words = text.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted)
var counts = [String: Int]()
for word in words {
if !word.isEmpty {
counts[word, default: 0] += 1
}
}
return (words, counts)
}
let text = "Hello, world! This is a test of word counting."
let result = countWords(text: text)
print("Words: \(result.words)")
print("Words count: \(result.counts)")
輸出
Words: ["hello", "", "world", "", "this", "is", "a", "test", "of", "word", "counting", ""] Words count: ["hello": 1, "counting": 1, "a": 1, "is": 1, "test": 1, "this": 1, "world": 1, "of": 1, "word": 1]
在這個例子中,`countWords` 函式接受一段文字字串,將其拆分為單個單詞,並計算每個單詞出現的次數。它返回一個包含兩個值的元組:一個單詞陣列和一個將每個單詞對映到其計數的字典。請注意,我們將所有單詞轉換為小寫以進行不區分大小寫的計數。
示例 3 - 查詢陣列中的最大值和最小值
import Foundation
func findMinMax(numbers: [Int]) -> (min: Int, max: Int)? {
guard !numbers.isEmpty else {
return nil
}
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number < min {
min = number
}
if number > max {
max = number
}
}
return (min, max)
}
let inputArray = [3, 5, 2, 7, 1, 8]
if let result = findMinMax(numbers: inputArray) {
print("Array: \(inputArray)")
print("Min value: \(result.min)")
print("Max value: \(result.max)")
}
輸出
Array: [3, 5, 2, 7, 1, 8] Min value: 1 Max value: 8
在這個例子中,`findMinMax` 函式接受一個整數陣列,並返回一個包含陣列中最小值和最大值的元組。如果陣列為空,則函式返回 nil。我們使用可選繫結(`if let result = ...`)來處理函式返回 nil 的情況。
示例 4 - 計算統計資料
import Foundation
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let inputArray = [5, 3, 100, 2, 10]
let statistics = calculateStatistics(scores: inputArray)
print("Input array: \(inputArray)")
print("Min value: \(statistics.min)")
print("Max value: \(statistics.max)")
print("Sum value: \(statistics.sum)")
輸出
Input array: [5, 3, 100, 2, 10] Min value: 2 Max value: 100 Sum value: 120
在這個例子中,`calculateStatistics` 函式接受一個整數陣列作為輸入,並返回一個包含三個值的元組:最低分數、最高分數和所有分數的總和。要返回元組,我們只需使用 `(value1, value2, value3)` 語法並將每個值用逗號分隔。
然後,您可以使用點語法和相應的屬性名稱(在本例中為 `statistics.min`、`statistics.max` 和 `statistics.sum`)訪問元組中的每個值。
結論
總之,元組是一個簡單的 Swift 資料結構,使您可以將多個值組合成單個複合值。元組可用於將多個值作為單個引數傳遞給函式,或從函式返回多個值。
元組成員可以命名以方便訪問,它們可以包含任何型別的值,包括其他元組。元組可以使您的程式碼更清晰易懂,同時提供一種簡單的方法來處理小的、相關的、組合的資料塊。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP