/
Contents.swift
82 lines (68 loc) · 1.75 KB
/
Contents.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//: [Index](Index)
/*:
[Swift Protocol Hub](https://mobidevtalk.com/swift-protocol-hub/)
[Protocol, Swift way of thinking](https://mobidevtalk.com/protocol-swift-practical-use-case/)
*/
import Foundation
/*:
A case study of Avengers
*/
protocol Avenger{
var name: String {get}
var speciality: String {get}
}
struct IronMan: Avenger{
var name = "Iron Man"
var speciality = "Iron Man got the coolest gadgets. Techie and smart 😎"
}
struct CaptainAmerica: Avenger{
var name = "Captain America"
var speciality = "Super Human power. Quick to heal, tough to beat. 💪"
}
struct Hulk: Avenger{
var name = "Hulk"
var speciality = "God like power. Good at smashing 🔥"
}
struct Thor: Avenger{
var name = "Thor"
var speciality = "God of Thunder ⚡️"
}
let initialTeam: [Avenger] = [IronMan(), CaptainAmerica(), Hulk(), Thor()]
initialTeam.forEach({ print($0.name) })
initialTeam.forEach({print($0.name + ": " + $0.speciality)})
/*:
Facilitating as needed
*/
protocol Defense: Avenger{
var defenseSystem: String { get }
}
extension IronMan: Defense{
var defenseSystem: String{
get{
return "The suite itself contains the defensive counter measure"
}
}
}
extension CaptainAmerica: Defense{
var defenseSystem: String{
get{
return "The shield is the main defense"
}
}
}
extension Thor: Defense{
var defenseSystem: String{
get{
return "The spinning Hammer is the defense"
}
}
}
let defenseHolder = initialTeam.compactMap { (avenger) -> Defense? in
if let defense = avenger as? Defense{
return defense
}
return nil
}
defenseHolder.forEach({
print($0.name + "'s Defense system is: " + $0.defenseSystem)
})