Swift 枚举使用

枚举

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
enum Media {
case Book(title: String, author: String, year: Int)
case Movie(title: String, director: String, year: Int)
case WebSite(url: NSURL, title: String)
}
let book = Media.Book(title: "20,000 leagues under the sea", author: "Jules Verne", year: 1870)

extension Media {
var mediaTitle: String {
switch self {
case .Book(title: let aTitle, author: _, year: _), let .Movie(aTitle, _, _):
return aTitle
case .WebSite(let url, let title):
return title
}
}
}
book.mediaTitle

extension Media {
var isFromJulesVerne: Bool {
switch self {
case .Book(title: _, author: "Jules Verne", year: _): return true
case .Movie(title: _, director: "Jules Verne", year: _): return true
default: return false
}
}
}
book.isFromJulesVerne

extension Media {
func checkAuthor(author: String) -> Bool {
switch self {
case .Book(title: _, author: author, year: _): return true
case .Movie(title: _, director: author, year: _): return true
default: return false
}
}
}
book.checkAuthor(author: "Jules Verne")


if case let Media.Book(title, _, _) = book {
print("This is a book named \(title)")
}
// guard case let Media.Book(_, _, year) = book else { ... }
// for case let Media.Book(_, _, year) in array { ... }
if case let Media.Book(_, _, year) = book, year > 2000 {
print("This is a book year \(year)")
}

鸣谢

本文标题:Swift 枚举使用

文章作者:史彦超

发布时间:2018年09月14日 - 22:09

最后更新:2021年07月20日 - 16:07

原始链接:https://doingself.github.io/2018/09/14/Swift-%E6%9E%9A%E4%B8%BE%E4%BD%BF%E7%94%A8/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Donate comment here