Swift2.2 学习笔记(十一) ___集合类型

数组
数组中使用有序列存储相同类型的多重数据。相同的值可以多次出现在一个数组不同的位置中。
Swift 数组对存储数据有具体要求。不同于oc的NSArray 和 NSMutableArray 类,他们可以存储任何类型的实例而且不供他们返回对象的任何本质信息。在 Swift 中, 数据值在被存储进入 个数组之前类型必须明确,方法是通过显式的类型标注或类型推断, 而且不是必须是 class 类型。

创建空数组

var someInts = [Int]()
print("SomeInts is of type [Int] with \(someInts.count) items.")
//prints:"SomeInts is of type [Int] with 0 items.\n"
//一个函数参数或者一个已经定义好类 型的常量或者变量,我们可以使用空数组语句创建一个空数组,它的写法很简单:[](一对 空方括号):
someInts.append(3)
// someInts 现在包含一个INT值
someInts = []
// someInts 现在是空数组,但是仍然是Int[]类型的。
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]


//创建特定大小并且所有数据都被默认的构造方法,可以把准备加入新数组的数据项数量(count)和适当类型的初始值(repeatedValue)传 入数组构造函数:
var anotherThreeDoubles = [Double](count: 3, repeatedValue: 2.5)
// 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]

数组构造语句

var shoppList:[String] = ["Eggs","Milk"]
print(shoppList)

var shoppList2 = ["Eggs","Milk"]
print(shoppList2)    //["Eggs", "Milk"]

访问和修改数组

print("The shoppling list contains \(shoppList.count) items")
//The shoppling list contains 2 items

使用布尔项isEmpty来作为检查count属性的值是否为0的捷径

if shoppList.isEmpty {
    print("The shopping list is empty.")
} else {
    print("The shopping list is not empty.")
}
//The shopping list is not empty.

使用append方法在数组后面添加新的数据项

shoppList.append("Flour")
print(shoppList) // ["Eggs", "Milk", "Flour"]

使用 加法赋值运算符(+=)

shoppList += ["Chocolate Spread","Cheese","Butter"]
print(shoppList)
//["Eggs", "Milk", "Flour", "Chocolate Spread", "Cheese", "Butter"]

用下标来改变 个已有索引值对应的数据值

shoppList[0] = "six eggs"
print(shoppList)

利用下标来一次改变一系列数据值

shoppList[4..<6] = ["Bananas","Apples"]
print(shoppList)

调用数组的insert(atIndex:)方法来在某个具体索引值之前添加数据项

shoppList.insert("Maple Syrup", atIndex: 0)
print(shoppList)

使用removeAtIndex方法来移除数组中的某一项

let mapleSyrup = shoppList.removeAtIndex(0)
//print(shoppList)

使用removeLast方法移除最后一项数组

let apples = shoppList.removeLast()
print(apples)  //Apples

数组遍历 for-in

for item in shoppList {
//    print(item)
}
/*
Apples
six eggs
Milk
Flour
Chocolate Spread
Bananas
*/

如果同时需要每个数据的值和索引值,可以使用全局 enumerate函数来进行数组遍历。

for(index, value) in shoppList.enumerate(){
    print("item \(index + 1 ):\(value)")
}
/*
item 1:six eggs
item 2:Milk
item 3:Flour
item 4:Chocolate Spread
item 5:Bananas
*/

创造并构建一个数组

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

someInts.append(3)
//someInts 现在包含一个INT值
print(someInts) //  [3]
//someInts 现在是空数组,但是仍然是Int[]类型的。
someInts = [] //   []
print(someInts)

把准备加入数组的数据项数量(count)和适当类型的初始值(repeatedValue)传入数组构造函数

var threeDoubles = [Double](count: 3,repeatedValue: 0.0)
print(threeDoubles)    //[0.0, 0.0, 0.0]

var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
print(anotherThreeDoubles)
  • Sets
  • Set是一种特殊的无序集合类型
  • Swift中的Set类型被写为Set,这里的T表示Set中允许存储的类型。
//创建并初始化空集合
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."


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

用数组字面量创建集合

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
//prints:{"Rock", "Classical", "Hip hop"}
  • 访问和修改一个Set
  • 为了找出一个Set中元素的数量,可以使用其只读属性count:
  • 使用布尔属性isEmpty 作为一个缩写形势去检查count属性是否为0
  • 你可以通过调用Set的insert(_:)方法来添加一个新元素
  • 用Set的remove(_:)方法去删除一个元素,也可以通过removeAll()方法删除所有元素
  • 使用contains(_:)方法去检查Set中是否包含一个特定的值
  • Set和Array不同的是,Set是无序的,可以通过调用sort()方法来进行排序
print("I have \(favoriteGenres.count) favorite music genres.")
// Prints "I have 3 favorite music genres."


  • Set之间的交并集
  • intersect:返回两个集合中都存在的数据
  • exclusiveror:返回两个集合各自特有的数据,忽略两个集合中都有的数据
  • union:返回两个集合中所有数据
  • subtract:返回不包含右边集合的所有数据
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).sort()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersect(evenDigits).sort()
// []
oddDigits.subtract(singleDigitPrimeNumbers).sort()
// [1, 9]
oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort()
// [1, 2, 9]
  • Set的比较
  • 使用(==)来判断2个集合中的值是否完全一样
  • isSubsetof,判断一个集合中的值是否被包含在另个集合中
  • isSupersetof,判断一个集合的所有值是否包含在另个集合中
  • isStrictSubsetof或者isStrictSupersetof,判断一个集合是否是另一个集合的子集,或者,父集合并且和特定集合不相等
  • isDisjointwith,判断是否不含相同的值
let houseAnimals: Set = ["��", "��"]
let farmAnimals: Set = ["��", "��", "��", "��", "��"]
let cityAnimals: Set = ["��", "��"]

houseAnimals.isSubsetOf(farmAnimals)
// true
farmAnimals.isSupersetOf(houseAnimals)
// true
farmAnimals.isDisjointWith(cityAnimals)
// true

字典

  • 字典是一种存储相同类型多重数据的存储器。每个值(value)都关联独特的键(key),键作为字典中的这个值数据的标识符。
  • 字典中的数据项并没有具体顺序。
  • Swift 的字典使用 Dictionary
var airports:Dictionary<String,String> = ["TYO":"Tokyo","DUB":"Dublin"]
print(airports)

print("The dictionary of airports contains \(airports.count) items")
//打印:The dictionary of airports contains 2 items

//分配新的合适类型的值
airports["LHR"] = "London"
print(airports)

//用下标愈发来改变特定键对应的值
airports["LHR"] = "London Heathrow"
print(airports)

字典

  • 字典是一种存储相同类型多重数据的存储器。每个值(value)都关联独特的键(key),键作为字典中的这个值数据的标识符。
  • 字典中的数据项并没有具体顺序。
  • Swift 的字典使用 Dictionary
if let oldValue = airports.updateValue("Dublin International", 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.")
}
//打印:The name of the airport is Dublin International.

使用下标语法来通过给某个键的对应值赋值为nil来从字典里溢出一个键值对

airports["APL"] = "Apple Internation"
print(airports)

airports["APL"] = nil
print(airports)

字典遍历 for-in。每一个字典中的数据项都由(key,value)元组形式返回。

for (airportCode, airportName) in airports {
    print("\(airportCode):\(airportName)")
}
/*
    打印:
    TYO:Tokyo
    LHR:London Heathrow
*/

// 通过访问keys或者values属性
for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
/*
打印:
Airport code: DUB
Airport code: TYO
Airport code: LHR
*/

for airportName in airports.values {
    print("Airport name: \(airportName)")
}

/*
打印:
Airport name: Dublin International
Airport name: Tokyo
Airport name: London Heathrow
*/

//使用某个字典的键集合或者值集合来作为某个接受Array实例API的参数
let airportCodes = Array(airports.keys)
print(airportCodes)
//["DUB", "TYO", "LHR"]

let airportNames = Array(airports.values)
print(airportNames)
//["Dublin International", "Tokyo", "London Heathrow"]

//创建一个空字典
var nameOfIntegers = Dictionary<Int,String>()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值