Swift相对Objective-C,突出了Struct的使用,可以用来声明复杂类型。虽然不能继承但是可以配合protocol和 extension 使用。一般面试者能答出值类型,但是可能是实践经验少的原因在下面的代码纠错翻车。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct ItemA {
var isSelect: Bool
var valueA: Int
var itemBList: [ItemB]?
}

struct ItemB {
var isSelect: Bool
var valueB: Int
}

extension ItemA {
func updateItemAState() {
let targetSelectState = !self.isSelect
self.isSelect = targetSelectState
if let _itemBList = itemBList {
for i in 0..<_itemBList.count {
_itemBList[i].isSelect = targetSelectState
}
}
}
}

以上代码有两个错误:

  • updateItemAState的function没有用mutating修饰,是无法编译通过
  • self.itemBList被if let语句重新赋值生成了新的变量,for循环更新对原始的ItemA.itemBList并没有起到作用。正确的代码如下:
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
struct ItemA {
var isSelect: Bool
var valueA: Int
var itemBList: [ItemB]?
}

struct ItemB {
var isSelect: Bool
var valueB: Int
}

extension ItemA {
mutating func updateItemAState() {
let targetSelectState = !self.isSelect
self.isSelect = targetSelectState
if var _itemBList = itemBList {
for i in 0..<_itemBList.count {
var item = _itemBList[i]
item.isSelect = targetSelectState
_itemBList[i] = item
}
self.itemBList = _itemBList
}
}
}