@frozen 和@unknown default

Posted by Genie on July 24, 2020

frozen意为冻结,是为Swift5的ABI稳定准备的一个字段,意味向编译器保证之后不会做出改变。为什么需要这么做以及这么做有什么好处,他们和ABI稳定是息息相关的.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@frozen public enum ComparisonResult : Int {
    case orderedAscending = -1
    case orderedSame = 0
    case orderedDescending = 1
}

@frozen public struct String {}

extension AVPlayerItem {
  public enum Status : Int {
    case unknown = 0
    case readyToPlay = 1
    case failed = 2
  }
}

对于可能变化的枚举,我们在列出所有case的时候还需要加上对 @unknown default 的判断,这一步会有编译器检查:

1
2
3
4
5
6
7
8
9
10
	switch currentItem.status {
    case .readyToPlay:
        /* code */
    case .failed:
        /* code */
    case .unknown:
        /* code */
    @unknown default:
        fatalError("not supported")
}