-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenerics_Part6.swift
130 lines (102 loc) · 1.97 KB
/
Generics_Part6.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
126
127
128
129
// Generics Subscripts
class College<T>
{
var classes: [T]
init(classes: [T]) {
self.classes = classes
}
subscript(index: Int) -> T {
return classes[index]
}
}
var clg = College(classes: ["Cse","Ece","Eee"])
print(clg[0])
struct College1<T>
{
var classes: [T]
init(classes: [T]) {
self.classes = classes
}
subscript(index: Int) -> T {
return classes[index]
}
}
var clg1 = College(classes: ["Cse","Ece","Eee"])
print(clg1[0])
protocol Edible
{
associatedtype type
var name: [type] {
get
}
subscript(ind: Int) -> type {
get
}
}
struct Fruit<type>: Edible {
var name: [type]
subscript(ind: Int) -> type {
return name[ind]
}
}
var fruit1 = Fruit(name: ["Apple", "Orange", "Mango"])
print(fruit1[0])
//---------------------------------
protocol Eatable {
associatedtype type
var name: [type] {
get
}
subscript(ind: Int) -> type {
get
}
}
extension Eatable {
subscript(ind: Int) -> type {
return name[ind]
}
}
struct Vegetable<type>: Eatable {
var name: [type]
}
var veg1 = Vegetable(name: ["Brinjal", "tomato"])
print(veg1[0])
//----------------------------
//generic class inheritance
class Person<type>{
var name: type
var age: type
init(name: type, age: type)
{
self.name = name
self.age = age
}
}
class Employee<type, U>: Person<type> {
var id: U
init(id: U, name: type, age: type)
{
self.id = id
super.init(name: name, age: age)
}
}
var emp = Employee(id: 100, name: "kala", age: "40")
type(of: emp.id)
type(of: emp.name)
type(of: emp.age)
// Inheriting associated type in protocol
protocol Namable {
associatedtype type1
var name: type1 {
get
}
}
protocol Identifiable: Namable {
var id: type1 {
get
}
}
struct Human<type1>: Identifiable {
var name: type1
var id: type1
}