ARTS-11.01

Algorithm

https://leetcode.com/problems/longest-common-prefix/submissions/

  • 将第一个字符串作为初始公共前缀,将其和每个字符串比较是否是其前缀,
    • 若不是则将公共前缀的最后一个字符移除,继续判断
    • 若是其前缀,则和下一个字符串比较
1
2
3
4
5
6
7
8
9
10
11
12
class Solution14 {
func longestCommonPrefixBest(_ strs: [String]) -> String {
guard let firstStr = strs.first else { return "" }
var commonPrefix = firstStr
for string in strs {
while !string.hasPrefix(commonPrefix) {
commonPrefix.removeLast()
}
}
return commonPrefix
}
}

Review

Understanding Date and DateComponents

网络中Date的概念严重依赖于时区和日历,若没有时区和日历,那么Date则毫无意义。因此在iOS中创建好Date对象之后,要对其设置时区和日历。

此外,DateFormatter可以帮助我们在date和文本表达之间转换,他会默认使用我们设备上的时区和日历,因此可以不显示设置,但是在使用的时候我们要清楚这一点。

由于Date是基于“时间间隔”概念的,因此在我们日常使用中并不是很方便,例如用Date描述“一个月之后”:Date().addingTimeInterval(60 * 60 * 24 * 30)。由于没有指定时区和日历,并且各地的每个月的天数并不一样,这样的描述就不会准确。这种情况下可以使用DateComponents

DateComponents描述的时间单位的概念,例如年月日时分秒。

使用方法:

  • 设置时间单位
  • 创建具体时间
1
2
3
4
5
6
7
8
var comps = DateComponents() // <1>
comps.timeZone = TimeZone(secondsFromGMT: 8) //要显式设置时区,否则不会生效
comps.day = 21
comps.month = 10
comps.year = 2020

let date = Calendar.current.date(from: comps)! // <2>
print(date) //"2020-10-21 00:00:00 +0000\n"

Tips

从服务端接收数据时,根据不同的类型,接收不同的数据结构

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
struct Data {
enum FruitType: Int {
case apple
case banana
}
enum Fruit {
case apple(Apple)
case banana(Banana)
case unknown
}
var type: Int
var fruit: Fruit
private enum CodingKeys: String, CodingKey {
case type
case fruit
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self) //拿到数据
self.type = try container.decode(Int.self, forKey: .type)
let fruitType: FruitType? = FruitType(rawValue: self.type)
switch fruitType {
case .apple:
self.fruit = .apple(try container.decode(Fruit.self, forKey: .fruit)) //解码苹果
case .banana:
self.fruit = .banana(try container.decode(Fruit.self, forKey: .fruit)) //解码香蕉
case .none:
self.fruit = .unknown
}
}
}

对一个临时的view截图

1
2
3
4
5
6
7
8
9
10
11
12
func generateShareImage() -> UIImage? {
let shareView = SomeView()
contentView.addSubview(shareView) //添加到界面上
shareView.snp.makeConstraints { (make) in //对其布局
make.top.leading.equalTo(contentView)
make.width.height.equalTo(57)
}
shareView.layoutIfNeeded() //更新
let snapshot = snapshotImage(with: shareView) //截图
shareView.removeFromSuperview() //移除
return snapshot
}

Share

Better print debugging with Xcode breakpoints

  • 通过设置断点的action,添加“Log Message”或者“Debugger Command”,来在代码运行期间打印信息或者变量值,从而不需要在代码中加上print然后重新编译,也不需要在代码中断时,在lldb通过po指令查看,非常方便
0%