-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathtype-casting.swift
More file actions
115 lines (88 loc) · 2.2 KB
/
type-casting.swift
File metadata and controls
115 lines (88 loc) · 2.2 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class Genre {
var name: String
init(name: String) { self.name = name }
}
class Classical : Genre {
}
class Pop : Genre {
}
var collection = [
Pop(name: "Hard Day's Night"),
Classical(name: "Canon in D"),
]
// The type of `collection` is inferred to be `Genre`
// Use `is` to check instance of.
for song in collection {
if song is Classical {
print("\(song.name) is classical!")
} else if song is Pop {
print("\(song.name) is poppy!")
}
}
/*
Hard Day's Night is poppy!
Canon in D is classical!
*/
// # Downcasting
// `as?` returns an optional (if you aren't sure the cast will succeed)
// `as` throws a runtime error if the cast doesn't succeed
for song in collection {
if let popSong = song as? Pop {
print("pop song")
} else if let classicalSong = song as? Classical {
print("classical song")
}
}
/*
pop song
classical song
*/
// # AnyObject
// Tons of Cocoa APIs (dicts, arrays, etc.) return `AnyObject`, a generic
// object wrapper. You have to use `as` to cast an `AnyObject` back to the
// type you expect.
// `AnyObject` doesn't allow primitives--only class-based objects.
var randomCollection: [AnyObject] = [
Pop(name: "Bishop Allen"),
Classical(name: "Bach"),
]
for item in randomCollection {
let songGenre = item as! Genre
print("\(songGenre.self)") // C11lldb_expr_03Pop (has 1 child) // C11lldb_expr_09Classical
print("\(songGenre.name)")
}
// Every item can also be downcasted in the for-loop
for item in randomCollection as! [Genre] {
print("\(item.name)")
}
/*
Bishop Allen
Bach
*/
// # Any
// `Any` allows primitives and class-based objects.
var groups = [Any]()
groups.append(1.0)
groups.append(1)
groups.append("string")
groups.append(Pop(name: "Long Winters"))
for item in groups {
switch item {
case let anInt as Int:
print("\(item) is an int")
case let aDouble as Double:
print("\(item) is a double")
case let aString as String:
print("\(item) is a string")
case let aGenre as Genre:
print("\(item) is a Genre")
default:
print("dunno")
}
}
/*
1.0 is a double
1 is an int
string is a string
C11lldb_expr_13Pop (has 1 child) is a Genre
*/