Swift教程之集合类型

集合类型

Swift有三种集合类型:数组、集合和字典。数组是有序集,集合是值唯一的无序集,字典是键值对的无序集。

CollectionTypes_intro_2x.png

Swift中的数组、集合和字典必须首先确定存储的值的类型,无法将错误类型插入集合类型中。


集合的可变性

将集合类型声明为常量let,集合不可修改,为不可变集合类型;声明为变量var,集合可增删改查,为可变集合类型。

注意

集合无需更改时,创建不可变集合可使代码易读,且Swift编译器对不可变集合作了性能优化。


数组

数组是存储相同类型值的有序列表,且同一个值可多次出现。

注意

Swift的Array类型与Foundation的NSArray类桥接。

数组类型的语法缩写

数组类型的语法为:

  • Array<Element>
  • [Element]

两种写法效果一致,但是Swift官方推荐后者。

创建空数组

使用初始化语法创建空数组:

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

若上下文已提供数组的类型信息,再次将该数组初始化时,可不指明数组存储类型,写为[]

someInts.append(3)
someInts = []

创建有默认值的数组

Swift的一个数组初始化器,可创建一个重复特定值特定次数的数组:

var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles 类型为 [Double], 等于 [0.0, 0.0, 0.0]

创建数组连接后的新数组

使用加法操作符(+)将两个类型兼容的数组相加来创建一个新数组:

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles 类型是 [Double], 等于 [2.5, 2.5, 2.5]
 
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles 推断为 [Double] 类型, 等于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

使用数组字面量创建数组

常用作法是使用数组字面量来初始化一个数组:

var shoppingList: [String] = ["Eggs", "Milk"]

类型推断可直接通过数组字面量推断数组的具体类型,因此通常会忽略数组类型的声明:

var shoppingList = ["Eggs", "Milk"]

获取和修改数组

通过数组的方法、属性或其下标语法获取和修改一个数组。

使用只读属性count获取数组的元素个数:

print("The shopping 数组包含 \(shoppingList.count) 个元素.")
// Prints "The shopping 数组包含 2 个元素s."

使用isEmpty属性判断数组元素个数是否为0:

if shoppingList.isEmpty {
    print("The shopping 数组为空.")
} else {
    print("The shopping 数组不为空.")
}
// Prints "The shopping 数组不为空."

调用**append(_:)**方法在数组末尾追加元素:

shoppingList.append("Flour")

使用 += 操作符也可给数组追加元素:

shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]

使用下标语法获取数组中的元素:

var firstItem = shoppingList[0]
// 第一个元素是 "Eggs"

下标语法可修改数组的现有元素值:

shoppingList[0] = "Six eggs"

下标语法可范围性修改数组元素,修改范围以给定的数组元素个数为主:

shoppingList[4...6] = ["Bananas", "Apples"]

**insert(_:at:)**方法可向数组插入新元素到指定索引:

shoppingList.insert("Maple Syrup", at: 0)

remove(at:)方法删除数组指定下标元素:

let mapleSyrup = shoppingList.remove(at: 0)

removeLast()方法删除数组的最后一个元素:

let apples = shoppingList.removeLast()

数组迭代

for-in循环遍历数组元素:

for item in shoppingList {
    print(item)
}

遍历数组时,若还需当前遍历的索引值,可使用enumerated()方法返回索引和索引的元素值组成的元组:

for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}


集合

集合是存储相同类型不同值的无序列表。当元素顺序不重要,或必须确保同一元素唯一存在时使用集合类型。

注意

Swift的Set类型与Foundation的NSSet类桥接。

Set类型的哈希值

为存储在集合中,元素类型必须是可哈希的。哈希值是所有比较想等对象的同一Int值,如a == b,则a.hashValue == b.hashValue

默认情况下,所有Swift的基本类型(如StringIntDoubleBool)都是可哈希的,可用作设置值类型或字典键类型。此外,没有关联值的枚举值是可哈希的。

注意

可使用自定义类型作为值类型或字典值类型,该类型必须遵循Swift标准库中的Hashable协议。并实现该协议的hashValue属性,也需提供==运算符的实现。

集合类型语法

Set类型写作Set,集合没有等效的简写形式。

创建和初始化空集合

使用初始化语法创建一个特定类型的空集合:

var letters = Set<Character>()
print("letters 类型为 Set<Character> ,有 \(letters.count) 个元素.")

若上下问中已提供集合的类型信息,则可通过使用空数组简写形式创建原集合:

letters.insert("a")
letters = []

使用数组字面量创建集合

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

与数组不同,从数组字面量无法推断其为集合类型,因此必须显示声明类型Set。但可从数组字面量中推断出元素类型,可不显示声明其元素类型:

var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

获取和修改集合

通过其方法和属性可获取和修改集合。

count属性获取集合的元素个数:

print("\(favoriteGenres.count)")

isEmpty属性判断集合元素个数是否为空:

if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}

调用**insert(_:)**方法插入新元素:

favoriteGenres.insert("Jazz")

调用**remove(_:)方法删除某个集合元素,当该元素存在时,返回该值,若不存在,返回nilremoveAll()**方法删除集合所有元素:

if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.")
} else {
    print("I never much cared for that.")
}

调用**contains(_:)**方法判断集合是否包含某元素:

if favoriteGenres.contains("Funk") {
    print("I get up on the good foot.")
} else {
    print("It's too funky in here.")
}
集合遍历

使用for-in循环遍历集合元素:

for genre in favoriteGenres {
    print("\(genre)")
}

集合遍历时没有特定顺序,使用sorted()方法使集合按照从小到大顺序遍历:

for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz


执行集合操作符

集合之间有很多基本操作,如并集、交集等。

集合的几本操作

下图表示ab集合操作及用阴影部分表示的操作结果:

setVennDiagram_2x.png

  • **intersection(_:)**方法创建一个包含两个集合共有元素的新集合。
  • **symmetricDifference(_:)**方法创建一个包含两个集合不同元素的新集合。
  • **union(_:)**方法创建一个包含两个集合所有元素的新集合。
  • **subtracting(_:)**方法创建一个包含所有不在另一个集合中的元素的新集合。

`

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]

`

集合元素和相等性

下图显示abc三个集合的相互关系:

setEulerDiagram_2x.png

  • ==操作符判断两个集合所有元素是否都想等。
  • isSubset(of:)方法判断某集合中所有元素是否全部包含在另一个集合中,即另一个集合的子集。
  • isSuperset(of:)方法判断某集合是否包含另一个集合的所有元素,即连一个集合的超集。
  • isStrictSubset(of:)isStrictSuperset(of:)方法判断一个集合是否是另一个集合的子集或超集,但不相等。
  • isDisjoint(with:)方法判断两个集合之间没有共有元素。

`

let houseAnimals: Set = ["?", "?"]
let farmAnimals: Set = ["?", "?", "?", "?", "?"]
let cityAnimals: Set = ["?", "?"]
 
houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true

`


字典

字典存储相同类型的键和相同类型的值相关联的无序集。

注意

Swift的Dictionary类型与Foundation框架的NSDictionary类桥接。

字典类型简写语法

Dictionary类型写作Dictionary<Key, Value>,其中key为键类型,value为值类型。简写形式为[Key: Value],Swift官方建议优先使用简写形式。

注意

字典的键类型必须遵循Hashable协议。

创建空字典

使用初始化语法创建一个空字典:

var namesOfIntegers = [Int: String]()

若上下文已提供类型信息,可直接使用[:]语法给原字典重新设置为空:

namesOfIntegers[16] = "sixteen"
namesOfIntegers = [:]

使用字典字面量创建字典

通常通过字典字面量,即将一个或多个键值对写入字典来创建字典:

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

通过字典字面量可推断出字典中元素的键值类型,因此可忽略字典类型的声明:

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

获取和修改字典

通过其方法、属性或下标语法可获取和修改字典。

只读属性count获取字典的元素个数:

print("The airports dictionary contains \(airports.count) items.")

isEmpty属性判断字典元素个数是否为0:

if airports.isEmpty {
    print("The airports 字典为空.")
} else {
    print("The airports 字典不为空.")
}
// 打印 "The airports 字典不为空."

可直接通过下标语法为字典添加适当类型的新元素:

airports["LHR"] = "London"

下标语法用来修改字典中特定键的值:

airports["LHR"] = "London Heathrow"

**updateValue(_:forKey:)方法用来更新或添加字典中特定键的值,若键存在,返回该值,若不存在,返回nil**。

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

下标语法可以直接获取字典中特定键的值,返回值类型的可选值,值存在,返回该值,不存在,返回nil

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}

通过下标语法将特定键的值赋值为nil来删除字典中相应的键值对:

airports["APL"] = "Apple International"
airports["APL"] = nil

或者调用removeValue(forKey:)方法删除相应键值对,同样返回值的可选类型:

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

字典遍历

使用for-in循环遍历字典元素,每次遍历以键值元组方式返回:

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

或者单独遍历字典的键或值:

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

使用keysvalues属性将字典的所有键或值单独创建一个数组:

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

使用sorted()方法使字典按照从小到大顺序遍历。

转载于:https://www.cnblogs.com/keqipu/p/7620066.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
嗨!对于 NSCollectionView 的 Swift 教程,我可以为你提供一些基本信息和指导。 NSCollectionView 是 macOS 开发中用于展示和管理集合视图的类。它类似于 iOS 中的 UICollectionView。下面是一些简单的步骤来使用 NSCollectionView: 1. 创建一个 NSCollectionView 实例:在你的视图控制器中创建一个 NSCollectionView 实例,并将其添加到你的视图层次结构中。 2. 设置数据源和代理:为你的 NSCollectionView 分配一个数据源和代理对象。数据源对象负责提供要展示的数据,而代理对象则处理用户与集合视图的交互。 3. 实现数据源方法:在你的数据源对象中,实现以下方法: - `numberOfSections(in:)`:返回集合视图中的分区数。 - `collectionView(_:numberOfItemsInSection:)`:返回指定分区中的项目数。 - `collectionView(_:itemForRepresentedObjectAt:)`:返回集合视图中指定索引路径的项目视图。 4. 实现代理方法(可选):在你的代理对象中,你可以实现一些可选方法来处理用户与集合视图的交互,例如选择项目、处理鼠标点击等。 5. 创建项目视图:创建一个自定义的 NSCollectionViewItem 子类,并在其中定义你想要展示的内容和样式。 6. 注册项目视图类:在你的 NSCollectionView 中注册你的自定义项目视图类,以便集合视图能够正确地创建和重用项目视图。 7. 刷新数据:通过调用 `reloadData()` 方法来刷新你的集合视图,以使它显示最新的数据。 这是一个简单的 NSCollectionView 实现的示例代码: ```swift import Cocoa class MyViewController: NSViewController, NSCollectionViewDataSource, NSCollectionViewDelegate { @IBOutlet weak var collectionView: NSCollectionView! override func viewDidLoad() { super.viewDidLoad() // 设置数据源和代理 collectionView.dataSource = self collectionView.delegate = self // 注册自定义项目视图类 collectionView.register(MyCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("MyItem")) // 刷新数据 collectionView.reloadData() } // MARK: - NSCollectionViewDataSource func numberOfSections(in collectionView: NSCollectionView) -> Int { return 1 } func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return dataArray.count } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier("MyItem"), for: indexPath) // 配置项目视图的内容 return item } // MARK: - NSCollectionViewDelegate // 处理用户与集合视图的交互 } class MyCollectionViewItem: NSCollectionViewItem { override func viewDidLoad() { super.viewDidLoad() // 配置项目视图的外观 } override var isSelected: Bool { didSet { // 处理选择状态变化 } } } ``` 以上是一个简单的 NSCollectionView 教程,希望能对你有所帮助!如果你还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值