Swift学习笔记——字符串的遍历及扩展

今天群里有人问到了Swift中for…in遍历字符串的问题,Interesting and learn about it.

我们知道,在Swift中,for……in的功能非常强大,那么该如何使用呢?

基本使用

首先我们写出如下代码:

let str = "1231312"
for i in str {
     print(i)
}

系统提示了一个错误:

Type 'String' does not conform to protocol 'SequenceType'


我们可以看到,这个错误提示我们'String'没有遵守'SequenceType'的协议。
那么'SequenceType'协议是什么呢?从官方文档中我们可以看到Array和Dictionary都是遵守这个协议的,那么我们先看看Array和Dictionary的实现。

let a: Array = [1,2,3,4]
for i in a {
    print(i)
}

let dic: [String: AnyObject] = ["a": 0, "b": 1, "c": 2]
for i in dic {
    print(i)
}

运行结果如下:
1 2 3 4 ("b", 1) ("a", 0) ("c", 2)
我们发现String的characters的属性是遵守这个协议的,所以:

let str: String = "Swift"
for i in str.characters {
    print(i)
}

运行结果如下:
S w i f t

拓展使用

在查看官方文档是,我们发现了这样一段代码:

enumerate()
Default Implementation
Returns a lazy SequenceType containing pairs (n, x), where ns are consecutive Ints starting at zero, and xs are the elements of base:

Declaration
@warn_unused_result func enumerate() -> EnumerateSequence

Discussion
for (n, c) in "Swift".characters.enumerate() {
print("(n): '(c)'")
}
0: 'S'
1: 'w'
2: 'i'
3: 'f'
4: 't'

这是什么意思呢?我们来跑一下代码:

for (n, c) in str.characters.enumerate() {
    print("\(n): '\(c)'")
}
        
for (n, c) in a.enumerate() {
    print("\(n): '\(c)'")
}
        
for (n, c) in dic.enumerate() {
    print("\(n): '\(c)'")
}

结果如下:
0: 'S' 1: 'w' 2: 'i' 3: 'f' 4: 't' 0: '1' 1: '2' 2: '3' 3: '4' 0: '("b", 1)' 1: '("a", 0)' 2: '("c", 2)'

可以看到,enumerate中记录的是索引及其对应的值的字典。我们可以利用它拿到当前值及其索引。

Tip:

一般情况下,我们这样遍历一个字典:

for (k, v) in dic {
    print("\(k) —— \(v)")
}

运行结果如下:
b —— 1 a —— 0 c —— 2

你可能感兴趣的:(Swift学习笔记——字符串的遍历及扩展)