-
Notifications
You must be signed in to change notification settings - Fork 1
/
ProtocolExamples.swift
61 lines (44 loc) · 1.14 KB
/
ProtocolExamples.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
51
52
53
54
55
56
57
58
59
60
61
// MUCH MORE WILL BE ADDED HERE, ALONG WITH EXPLANATIONS
protocol Bird : CustomStringConvertible
{
var name: String { get }
var canFly: Bool { get }
}
extension Bird
{
var canFly: Bool { return self is Flyable }
}
extension CustomStringConvertible where Self: Bird
{
var description: String {
return canFly ? "I can fly" : "Guess I’ll just sit here :["
}
}
extension Motorcycle: Racer {}
func topSpeed<R: Sequence>(of racers: R) -> Double where R.Iterator.Element == Racer
{
return racers.max(by: { $0.speed < $1.speed })?.speed ?? 0
}
topSpeed(of: racers[1...3])
extension Sequence where Iterator.Element == Racer
{
func topSpeed() -> Double {
return self.max(by:{ $0.speed < $1.speed })?.speed ?? 0
}
}
racers[3…4].topSpeed()
protocol Score: Equatable, Comparable {
var value: Int { get }
}
extension Score {
static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.value == rhs.value
}
static func <(lhs: Self, rhs: Self) -> Bool {
return lhs.value < rhs.value
}
}
struct RacingScore: Score {
let value: Int
}
RacingScore(value: 40) > RacingScore(value: 30)