集合类型
- 数组(Array)
- 集合(Set)
- 字典(Dictionary)
前言
Swift 语言提供Arrays有序的数据、Sets 无序无重复数据和Dictionaries 无序键值对三种基本的集合类型用来存储集合数据。数组是有序数据的集。集合是无序无重复数据的集。字典是无序的键值对的集
Swift 语言提供 Arrays、Sets 和 Dictionaries 中存储数据类型必须明确。 这以为着我们不能把不正确的数据类型插入其中。同事这也说明我们完全可以对取回值得类型非常自信
数组集合字典对比
相同点
创建方式:构造器方法
字面量方法
数组操作:都可以增删改查不同点
数组有序,相同值可以多次出现
集合 无序 不会出现相同值
字典 以键值对方法出现
以下感觉比较重要的属性以及方法列举出来
- 数组初始化、修改:
// 创建空数组
var someints = [Int]()
// 创建带有默认值的数组
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
//通过两个数组相加创建一个数组
var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
var sixDoubles = threeDoubles + anotherThreeDoubles
print(sixDoubles) // [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
//添加新数据
shoppingList.append("Flour")
// 使用加法复制运算符 += “”
shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread","Cheese","Butter"]
// 使用下标 访问数组中的数据-
var firstItem = shoppingList[0]
// 使用 insert(_ : atIndex:) 添加数据
shoppingList.insert("Maple Syrup", atIndex: 0)
// 删除数据
// 使用 removeAtIndex(_:)移除数组中的某一项
let mapleSyrup = shoppingList.removeAtIndex(0)
print(mapleSyrup) // “Maple Syrup”
// 移除最后一项
shoppingList.removeLast()
shoppingList.removeFirst()