学计算机的那个

不是我觉到、悟到,你给不了我,给了也拿不住;只有我觉到、悟到,才有可能做到,能做到的才是我的.

0%

Swift面试高级

一个 Sequence 的索引是不是一定从 0 开始?

不一定, 两个 for in 并不能保证都是从 0 开始, 且输出结果一致, 官方文档如下:

1
2
3
4
5
Repeated Access  
The Sequence protocol makes no requirement on conforming types regarding
whether they will be destructively consumed by iteration. As a
consequence, don’t assume that multiple for-in loops on a sequence
will either resume iteration or restart from the beginning:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/系统方法调用
print("start----")
let numbers = [2, 3, 5, 7]
var numbersIterator = numbers.makeIterator()
while let num = numbersIterator.next() {
print(num)
}
print("midle----")
while let num = numbersIterator.next() {
print(num)
}
print("end----")

输出:
start----
2
3
5
7
midle----
end----

数组都实现了哪些协议

MutableCollection, 实现了可修改的数组, 如 a[1] = 2
ExpressibleByArrayLiteral, 实现了数组可以从[1, 2, 3] 这种字面值初始化的能力

编译选项 whole module optmization 优化了什么

编译器可以跨文件优化编译代码, 不局限于一个文件

下面代码中 mutating 的作用是什么

1
2
3
4
5
6
7
struct Person {
var name: String {
mutating get {
return store
}
}
}

让不可变对象无法访问 name 属性

为什么数组索引越界会崩溃,而字典用下标取值时 key 没有对应值的话返回的是 nil 不会崩溃

数组的对象的储蓄地址是连续的,如果越界了,那取到的地址不一定可用,所以报错。字典的key并没有对应确定的内存地址,所以是安全的.

1
2
3
4
5
6
7
struct Array<Element> {
subscript(index: Int) -> Element
}

struct Dictionary<Key: Hashable, Value> {
subscript(key: Key) -> Value?
}

lazy 懒加载的实现

lazy懒加载,oc中实利用get方法实现, swift利用闭包实现.比如

1
2
3
4
5
6
7
private lazy var navLeftButton = { () -> UIButton in
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
btn.setImage(UIImage(named:"back"), for: .normal)
btn.addTarget(self, action: #selector(self.back), for: .touchUpInside)
return btn
}()

Swift中的常量和OC中的常量有啥区别?

OC中的常量(const)是编译期决定的,Swift中的常量(let)是运行时确定的

map 与 flatmap 的区别

map不能将元素映射成可选类型,flatmap可以

如何自定义模式匹配

自定义的模式匹配和语法糖

计算属性 和 存储属性

计算属性可以用于类、结构体和枚举,而存储属性只能用于类和结构体。

参考

2022新Swift 面试题