Swift-集合類型

Swift提供了三種主要的集合類型,稱為數(shù)組,集合和字典,用于存儲值的集合。數(shù)組是值的有序集合。集是唯一值的無序集合。字典是鍵-值關(guān)聯(lián)的無序集合

image.png

Swift中的數(shù)組,集合和字典始終清楚它們可以存儲的值和鍵的類型。這意味著您不能將錯(cuò)誤類型的值錯(cuò)誤地插入到集合中。這也意味著您可以確定將從集合中檢索的值的類型。

集合的可變性

如果創(chuàng)建數(shù)組,集合或字典,并將其分配給變量,則創(chuàng)建的集合將是mutable。這意味著您可以在創(chuàng)建集合后通過添加,刪除或更改集合中的項(xiàng)目來更改(或變異)集合。如果將數(shù)組,集合或字典分配給常量,則該集合是不可變的,并且其大小和內(nèi)容無法更改

數(shù)組

創(chuàng)建一個(gè)空數(shù)組

var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."

創(chuàng)建具有默認(rèn)值的數(shù)組
Swift的Array類型還提供了一個(gè)初始化程序,用于創(chuàng)建一個(gè)特定大小的數(shù)組,并將其所有值設(shè)置為相同的默認(rèn)值。您向初始化程序傳遞了適當(dāng)類型的默認(rèn)值(稱為repeating):以及該值在新數(shù)組中重復(fù)的次數(shù)(稱為count)

var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

您可以使用加法運(yùn)算符(+)將兩個(gè)具有兼容類型的現(xiàn)有數(shù)組加在一起,從而創(chuàng)建一個(gè)新數(shù)組。從添加到一起的兩個(gè)數(shù)組的類型推斷出新數(shù)組的類型:

var threeDoubles = Array(repeating: 0.0, count: 3)
        // threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
        print(threeDoubles)
        
        var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
        // anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]

        var sixDoubles = threeDoubles + anotherThreeDoubles
        // sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
        
        print(sixDoubles)

您可以通過調(diào)用數(shù)組的append(_:)方法將新項(xiàng)目添加到數(shù)組的末尾:

shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes

或者,使用附加賦值運(yùn)算符(+=)附加一個(gè)或多個(gè)兼容項(xiàng)的數(shù)組:

shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items
image.png
image.png

如上圖 推斷是是字符呢串 ,所以不能插入00

插入第一個(gè)元素
 shoppingList.insert("00", at: 0)
 print(shoppingList)

刪除第一個(gè)元素
shoppingList.remove(at: 0)

遍歷數(shù)組

for item in shoppingList {
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas



for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas

Set

創(chuàng)建和初始化一個(gè)空集

var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// Prints "letters is of type Set<Character> with 0 items."

//插入一個(gè)值
letters.insert("a")
print(letters)

//刪除一個(gè)值
letters.remove("a")
print(letters)

執(zhí)行集合操作


image.png

使用該intersection(:)方法創(chuàng)建僅具有兩個(gè)集合共有的值的新集合。
使用該symmetricDifference(
:)方法創(chuàng)建一個(gè)新集合,其中兩個(gè)集合中都有一個(gè)值,但不能同時(shí)包含兩個(gè)集合中的值。
使用該union(:)方法創(chuàng)建一個(gè)包含兩個(gè)集合中所有值的新集合。
使用該subtracting(
:)方法創(chuàng)建一個(gè)新集合,其值不在指定集合中。


let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]

設(shè)定會員資格和平等


image.png

使用“等于”運(yùn)算符(==)確定兩組是否包含所有相同的值。
使用該isSubset(of:)方法確定集合中的所有值是否都包含在指定集合中。
使用該isSuperset(of:)方法確定集合是否包含指定集合中的所有值。
使用isStrictSubset(of:)或isStrictSuperset(of:)方法確定集合是子集還是超集,但不等于指定的集合。
使用該isDisjoint(with:)方法確定兩個(gè)集合是否沒有共同的值。

let houseAnimals: Set = ["??", "??"]
let farmAnimals: Set = ["??", "??", "??", "??", "??"]
let cityAnimals: Set = ["??", "??"]

houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true

Dictionary

創(chuàng)建一個(gè)空字典

var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary



namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

用字典文字創(chuàng)建字典

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

訪問和修改字典

airports["LHR"] = "London"
// the airports dictionary now contains 3 items


airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"


if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}
// Prints "The old value for DUB was Dublin."


if let removedValue = airports.removeValue(forKey: "DUB") {
    print("The removed airport's name is \(removedValue).")
} else {
    print("The airports dictionary does not contain a value for DUB.")
}
// Prints "The removed airport's name is Dublin Airport."

遍歷字典

for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// LHR: London Heathrow
// YYZ: Toronto Pearson
for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
// Airport code: LHR
// Airport code: YYZ

for airportName in airports.values {
    print("Airport name: \(airportName)")
}
// Airport name: London Heathrow
// Airport name: Toronto Pearson
let airportCodes = [String](airports.keys)
// airportCodes is ["LHR", "YYZ"]

let airportNames = [String](airports.values)
// airportNames is ["London Heathrow", "Toronto Pearson"]

OK Swift-集合類型 分享到此 。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容