Swift - 复杂数据类型说明(数组,字典,结构体,枚举)

注:代码已升级至Swift4

数组Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
var types = ["none","warning","error"]  //省略类型的数组声明

var menbers = [String]() //声明一个空数组

menbers.append("six") //添加元素
menbers += ["seven"] //添加元素
menbers.insert("one", at:0) //指定位置添加元素

menbers[0] = "message" //通过下标修改数组中的数据
menbers[0...2] = ["message","hangge","com"] //通过小标区间替换数据(前3个数据)

menbers.count //获取数组元素个数
menbers.isEmpty //判断数组是否为空

//交换元素位置(第2个和第3个元素位置进行交换)
menbers.swapAt(1, 2)

menbers.remove(at: 2) //删除下标为2的数组
menbers.removeLast() //删除最后一个元素
menbers.removeAll(keepingCapacity: true) //删除数组中所有元素

let addStringArr = types + menbers //数组组合

//使用for in 实现数组遍历
for value in menbers{
print("\(value)");
}

//通过enumerate函数同时遍历数组的所有索引与数据
for (index,value) in menbers.enumerated(){
print("索引:\(index) 数据:\(value)");
}

//过滤数组元素
let newTypes = types.filter { $0.count < 6 } //["none", "error"]

//创建包含100个元素的数组 ["条目0", "条目1" ... "条目99"]
let items = Array(0..<100).map{ "条目\($0)"}

//创建并初始化包含1024个Double元素的数组
var xTRe: [Double] = [Double]()
xTRe = [Double](count:Int(1024), repeatedValue:0.0)

字典Dictionary(即键值对)

基本用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var empty = [String: Int]()  //建立个空字典

var myDic = ["name":"hangge",
"url":"hangge.com"] //声明一个字典

myDic["address"] = "china" //添加或修改key值
myDic.removeValue(forKey: "name") //删除"name"这个key值
myDic["name"] = nil //同样可以删除"name"这个key值
myDic.keys //访问字典的key集合
myDic.values //访问字典的values集合

//遍历字典
for (key,value) in myDic {
print("\(key):\(value)");
}

//只遍历字典的键(key)
for key in myDic.keys {
print("\(key)");
}

//只遍历字典的值(value)
for value in myDic.values {
print("\(value)");
}

//过滤字典元素
let dict2 = dict.filter { $0.value < 7 } //["Pear": 6]

其它几种创建字典的方法

(1)通过元组创建字典

1
2
3
let tupleArray = [("Monday", 30),  ("Tuesday", 25),  ("Wednesday", 27)]
let dictionary = Dictionary(uniqueKeysWithValues: tupleArray)
print(dictionary) //["Monday": 30, "Tuesday": 25, "Wednesday": 27]

(2)通过键值序列创建字典

1
2
3
let names = ["Apple", "Pear"]
let prices = [7, 6]
let dict = Dictionary(uniqueKeysWithValues: zip(names, prices)) //["Pear": 6, "Apple": 7]

(3)只有键序列、或者值序列创建字典

1
2
3
4
5
let array = ["Monday", "Tuesday", "Wednesday"]
let dict1 = Dictionary(uniqueKeysWithValues: zip(1..., array))
let dict2 = Dictionary(uniqueKeysWithValues: zip(array, 1...))
print("dict1:\(dict1)")
print("dict2:\(dict2)")

(4)字典分组(比如下面生成一个以首字母分组的字典)

1
2
3
let names = ["Apple", "Pear", "Grape", "Peach"]
let dict = Dictionary(grouping: names) { $0.first! }
print(dict) //["P": ["Pear", "Peach"], "G": ["Grape"], "A": ["Apple"]]

重复键的处理

(1)zip配合速记+可以用来解决重复键的问题(相同的键值相加)

1
2
3
let array = ["Apple", "Pear", "Pear", "Orange"]
let dic = Dictionary(zip(array, repeatElement(1, count: array.count)), uniquingKeysWith: +)
print(dic) // ["Pear": 2, "Orange": 1, "Apple": 1]

(2)下面使用元组创建字典时,遇到相同的键则取较小的那个值

1
2
3
let duplicatesArray = [("Monday", 30),  ("Tuesday", 25),  ("Wednesday", 27), ("Monday", 28)]
let dic = Dictionary(duplicatesArray, uniquingKeysWith: min)
print(dic) // ["Monday": 28, "Tuesday": 25, "Wednesday": 27]

字典合并

想要将一些序列、或者字典合并到现有的字典中,可以借助如下两个合并方法:

merge(: uniquingKeysWith:):这种方法会修改原始Dictionary
merging(
: uniquingKeysWith:):这种方法会创建并返回一个全新的Dictionary

1
2
3
4
5
6
7
8
9
10
11
var dic = ["one": 10, "two": 20]

//merge方法合并
let tuples = [("one", 5), ("three", 30)]
dic.merge(tuples, uniquingKeysWith: min)
print("dic:\(dic)")

//merging方法合并
let dic2 = ["one": 0, "four": 40]
let dic3 = dic.merging(dic2, uniquingKeysWith: min)
print("dic3:\(dic3)")

默认值

(1)过去我们如果希望当某个字典值不否存在时,使用一个指定的默认值,这个通常会使用if let来判断实现。

1
2
3
4
5
6
7
8
let dic = ["apple": 1, "banana": 2 ]
var orange:Int
if let value = dic["orange"] {
orange = value
}else{
orange = 0
}
print(orange)

(2)到了 Swift4,我们可以直接指定一个默认值,如果不存在该键值时名,会直接返回这个值。下面代码的效果同上面是一样的。

1
2
3
let dic = ["apple": 1, "banana": 2 ]
let orange = dic["orange", default:0]
print(orange)

(3)下面是统计一个字符串中所有单词出现的次数。可以看到了有了默认值,实现起来会简单许多。

1
2
3
4
5
6
let str = "apple banana orange apple banana"
var wordsCount: [String: Int] = [:]
for word in str.split(separator: " ") {
wordsCount["\(word)", default: 0] += 1
}
print(wordsCount)

结构体struct

1
2
3
4
5
6
7
8
9
10
//创建一个结构体
struct BookInfo{
var ID:Int = 0
var Name:String = "Defaut"
var Author:String = "Defaut"
}

var book1:BookInfo //默认构造器创建结构体实例
var book2 = BookInfo(ID:0021,Name:"航歌",Author:"hangge") //调用逐一构造器创建实例
book2.ID = 1234 //修改内部值

枚举enum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
enum CompassPoint {
case north
case south
case east
case west
}
var directionToHead = CompassPoint.west

enum Planet: Int {
case mercury = 1
case venus = 2
case earth = 3
}
let earthsOrder = Planet.earth.rawValue //rawValue来获取他的原始值:3
let possiblePlanet = Planet(rawValue: 2) //通过原始值来寻找所对应的枚举成员:Venus

enum Direction {
case up
case down

func description() -> String{
switch(self){
case .up:
return "向上"
case .down:
return "向下"
}
}
}
print(Direction.up.description())

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :