-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenerics_Part3.swift
125 lines (96 loc) · 2.06 KB
/
Generics_Part3.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
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
116
117
118
119
120
121
122
123
124
125
//Associated Types
protocol Flyable
{
associatedtype Obj
associatedtype Bird
var objName: Obj {
get
}
var birdName: Bird
{
get
}
func objFly() -> Obj
func birdFly() -> Bird
}
class FlyingClass<Obj, Bird>
{
var birdName: Bird
var objName: Obj
func objFly() -> Obj {
return objName
}
init(objName: Obj, birdName: Bird) {
self.objName = objName
self.birdName = birdName
}
}
var class1 = FlyingClass(objName: "Aeroplane", birdName: "Sparrow")
var temp2 = class1.objFly()
print(temp2)
print(type(of: temp2))
//Extending an existing type to specify associated type
var temp3 = class1.birdFly() // func used before defined in extension
print(temp3)
print(type(of: temp3))
extension FlyingClass: Flyable
{
func birdFly() -> Bird {
return birdName
}
}
var temp1 = class1.birdFly()
print(temp1)
print(type(of: temp1))
//Adding constraints to an associated type
protocol Growable
{
associatedtype Obj: Hashable
func grow(name: Obj) -> Obj
}
struct Leaves: Hashable
{
var color: String
}
class Plant<Obj: Hashable>: Growable{
var stru: Obj
func grow(name: Obj) -> Obj {
print(type(of: name))
return name
}
init(stru: Obj)
{
self.stru = stru
}
}
var plant2 = Plant(stru: Leaves(color: "Green"))// - error Generic class 'Plant' requires that 'Leaves' conform to 'Hashable'
print(plant2.grow(name: Leaves(color: "Brown")))
var plant1 = Plant(stru: "Neem")
print(plant1.grow(name: "Neem"))
//default implementation - protocol
protocol Xyz
{
func function1()
func function2()
}
class User: Xyz
{
/*func function3(){
print("FUNCTION3")
}*/
}
extension Xyz
{
func function1() {
print("Function1")
}
func function2() {
print("Function2")
}
func function3(){ // can also add new implementation of method in extension for protocol and it is defaullt one
print("function3")
}
}
var user1 = User()
user1.function1()
user1.function3()