Swift 數(shù)組、字典和集合
本文我們將介紹 Swift 中的變量、常量和數(shù)據(jù)類型。如果你尚未安裝 Xcode 和配置 Swift 開(kāi)發(fā)環(huán)境,請(qǐng)您先閱讀這篇文章。
接下來(lái),我們啟動(dòng) Xcode,然后選擇 "File" > "New" > "Playground"。創(chuàng)建一個(gè)新的 Playground 并命名為 "Collections"。
Arrays
數(shù)組是一種用于存儲(chǔ)相同類型元素的有序集合,是 Swift 中常用的數(shù)據(jù)結(jié)構(gòu)之一。讓我們通過(guò)比較 Swift 和 TypeScript 中的示例,了解如何使用數(shù)組以及它們的基本操作。
創(chuàng)建一個(gè)數(shù)組
Swift Code
var numbers = [1, 2, 3, 4, 5]
// 或者 var numbers: [Int] = [1, 2, 3, 4, 5]
var fruits = ["Apple", "Banana", "Orange"]
// 或者 var fruits: [String] = ["Apple", "Banana", "Orange"]
TypeScript Code
let numbers = [1, 2, 3, 4, 5];
// 或者 let numbers: number[] = [1, 2, 3, 4, 5];
let fruits = ["Apple", "Banana", "Orange"];
// 或者 let fruits: string[] = ["Apple", "Banana", "Orange"];
訪問(wèn)和修改數(shù)組元素
在 Swift 和 TypeScript 中,您可以通過(guò)下標(biāo)訪問(wèn)和修改數(shù)組元素。
Swift Code
let firstNumber = numbers[0]
// firstNumber: 1
numbers[1] = 10
TypeScript Code
const firstNumber = numbers[0];
// firstNumber: 1
numbers[1] = 10;
添加元素
在 Swift 中,使用 append 方法添加元素。而在 TypeScript 中,是使用 push 方法。
Swift Code
fruits.append("Grapes")
// fruits: ["Apple", "Banana", "Orange", "Grapes"]
TypeScript Code
fruits.push("Grapes");
// fruits: ["Apple", "Banana", "Orange", "Grapes"]
刪除元素
在 Swift 中,使用 remove(at:) 方法刪除指定位置的元素。而在 TypeScript 中,是使用 splice 方法。
Swift Code
fruits.remove(at: 1)
// fruits: ["Apple", "Orange", "Grapes"]
TypeScript Code
fruits.splice(1, 1);
// fruits: ["Apple", "Orange", "Grapes"]
獲取數(shù)組長(zhǎng)度
在 Swift 中,使用 count 屬性獲取數(shù)組長(zhǎng)度。而在 TypeScript 中,是使用 length 屬性。
Swift Code
let count = fruits.count
TypeScript Code
const count = fruits.length;
遍歷數(shù)組元素
在 Swift 中,可以使用 for-in 遍歷數(shù)組。而在 TypeScript 中,可以使用 for-of 循環(huán)。
Swift Code
for fruit in fruits {
print("I like \(fruit)s")
}
/**
Output:
I like Apples
I like Oranges
I like Grapess
*/
TypeScript Code
for (const fruit of fruits) {
console.log(`I like ${fruit}s`);
}
/**
Output:
"I like Apples"
"I like Oranges"
"I like Grapess"
*/
字典
字典是一種用于存儲(chǔ)鍵值對(duì)的集合,它允許你通過(guò)鍵來(lái)快速檢索值。
創(chuàng)建一個(gè)字典
在 Swift 中,字典使用 [Key: Value] 的語(yǔ)法來(lái)聲明,其中 Key 是鍵的數(shù)據(jù)類型,Value 是值的數(shù)據(jù)類型。
Swift Code
var studentScores = ["Alice": 95, "Bob": 87, "Charlie": 90]
TypeScript Code
let studentScores: { [key: string]: number } = { "Alice": 95, "Bob": 87, "Charlie": 90 };
訪問(wèn)和修改字典元素
在 Swift 和 TypeScript 中,你可以通過(guò)鍵訪問(wèn)和修改字典元素。
Swift Code
let aliceScore = studentScores["Alice"]
studentScores["Bob"] = 92
// studentScores: ["Alice": 95, "Bob": 92, "Charlie": 90]
TypeScript Code
const aliceScore = studentScores["Alice"];
studentScores["Bob"] = 92;
// studentScores: {"Alice": 95, "Bob": 92, "Charlie": 90}
添加鍵值對(duì)
在 Swift 和 TypeScript 中,使用下標(biāo)賦值的方式添加鍵值對(duì)。
Swift Code
studentScores["David"] = 88
// studentScores: ["Charlie": 90, "Alice": 95, "Bob": 92, "David": 88]
TypeScript Code
studentScores["David"] = 88;
// studentScores: {"Charlie": 90, "Alice": 95, "Bob": 92, "David": 88}
刪除鍵值對(duì)
在 Swift 中,使用 removeValue(forKey:) 方法刪除指定鍵的鍵值對(duì)。而在 TypeScript 中,是使用 delete 操作符刪除鍵值對(duì)。
Swift Code
studentScores.removeValue(forKey: "Charlie")
// studentScores: ["David": 88, "Bob": 92, "Alice": 95]
TypeScript Code
delete studentScores["Charlie"];
// studentScores: {"David": 88, "Bob": 92, "Alice": 95}
獲取鍵和值的集合
在 Swift 中,通過(guò) keys 和 values 屬性獲取字典的鍵和值的集合。而在 TypeScript 中,是使用 Object.keys 和 Object.values 方法。
Swift Code
let allKeys = Array(studentScores.keys)
let allValues = Array(studentScores.values)
// allKeys: ["David", "Bob", "Alice"]
// allValues: [88, 92, 95]
TypeScript Code
const allKeys: string[] = Object.keys(studentScores);
const allValues: number[] = Object.values(studentScores);
// allKeys: ["Alice", "Bob", "David"]
// allValues: [95, 92, 88]
遍歷字典
在 Swift 和 TypeScript 中,都可以通過(guò) for-in 循環(huán)遍歷字典。
Swift Code
for (name, score) in studentScores {
print("\(name) scored \(score)")
}
/**
Output:
Alice scored 95
Bob scored 92
David scored 88
*/
TypeScript Code
for (const name in studentScores) {
const score: number = studentScores[name];
console.log(`${name} scored ${score}`);
}
/**
Output:
"Alice scored 95"
"Bob scored 92"
"David scored 88"
*/
集合
集合是一種無(wú)序、無(wú)重復(fù)元素的集合類型。在 Swift 中,集合通過(guò) Set 類型表示。
創(chuàng)建一個(gè)集合
Swift Code
var numberSet: Set<Int> = [1, 2, 3, 4, 5]
TypeScript Code
let numberSet: Set<number> = new Set([1, 2, 3, 4, 5]);
添加元素
在 Swift 中,使用 insert 方法向集合中添加元素。而在 TypeScript 中,使用 add 方法。
Swift Code
numberSet.insert(6)
// numberSet: [3, 4, 5, 1, 2, 6]
TypeScript Code
numberSet.add(6);
// numberSet: {1, 2, 3, 4, 5, 6}
移除元素
在 Swift 中,使用 remove 方法移除集合中的元素。而在 TypeScript 中,使用 delete 方法。
Swift Code
numberSet.remove(3)
// numberSet: [5, 2, 1, 4, 6]
TypeScript Code
numberSet.delete(3);
// numberSet: {1, 2, 4, 5, 6}
遍歷集合
在 Swift 中,可以使用 for-in 循環(huán)遍歷集合。而在 TypeScript 中,可以通過(guò) forEach 方法遍歷集合。
Swift Code
for number in numberSet {
print("Number is \(number)")
}
/**
Output:
Number is 2
Number is 1
Number is 5
Number is 6
Number is 4
*/
TypeScript Code
numberSet.forEach((number) => {
console.log(`Number is ${number}`);
});
/**
Output:
"Number is 1"
"Number is 2"
"Number is 4"
"Number is 5"
"Number is 6"
*/
集合交集
在 Swift 中,使用 intersection 方法獲取兩個(gè)集合的交集。而在 TypeScript 中,可以使用 Set 構(gòu)造函數(shù)和 filter 方法。
Swift Code
let anotherSet: Set<Int> = [4, 5, 6]
let intersection = numberSet.intersection(anotherSet)
// numberSet: [1, 5, 4, 2, 6]
// anotherSet: [5, 4, 6]
// intersection: [5, 4, 6]
TypeScript Code
const anotherSet: Set<number> = new Set([4, 5, 6]);
const intersection: Set<number> = new Set([...numberSet].filter(x => anotherSet.has(x)));
// numberSet: {1, 2, 4, 5, 6}
// anotherSet: {4, 5, 6}
// intersection: {4, 5, 6}
集合并集
在 Swift 中,使用 union 方法獲取兩個(gè)集合的并集。
Swift Code
let union = numberSet.union(anotherSet)
// numberSet: [5, 1, 4, 2, 6]
// anotherSet: [4, 5, 6]
// union: [5, 1, 4, 2, 6]
TypeScript Code
const union: Set<number> = new Set([...numberSet, ...anotherSet]);
// numberSet: {1, 2, 4, 5, 6}
// anotherSet: {4, 5, 6}
// union: {1, 2, 4, 5, 6}
集合差集
在 Swift 中,使用 subtracting 方法獲取兩個(gè)集合的差集。而在 TypeScript 中,可以使用 Set 構(gòu)造函數(shù)和 filter 方法。
Swift Code
let difference = numberSet.subtracting(anotherSet)
// numberSet: [6, 2, 4, 1, 5]
// anotherSet: [5, 6, 4]
// difference: [1, 2]
TypeScript Code
const difference: Set<number> = new Set([...numberSet].filter(x => !anotherSet.has(x)));
// numberSet: {1, 2, 4, 5, 6}
// anotherSet: {4, 5, 6}
// difference: {1, 2}
本文我們介紹 Arrays, Dictionaries 和 Sets 三種集合類型等相關(guān)的知識(shí)。通過(guò)與 TypeScript 語(yǔ)法的對(duì)比,希望能幫助您更好地理解 Swift 的相關(guān)特性。