Normally when you work with Swift you are sure of some specific types that you are using in your code. But sometimes you are not sure what type will be used or it can be any type that you want to use in your code. That's why you use Generics which gives you a way to achieve this task with ease. If you are to use Generics, you must add <T> after a function name.After then you can substitute T in place of type name. Generics in Swift are just like Templates in C++ which do the same task as Generics in Swift. Lets have an example we are using two classes with inheritance"Library" && "users":
class Library {
class Library {
var name: String = "Oxford"
var numberOfBooks = 200
func profile() -> String {
return "In \(self.name) library there are \(numberOfBooks) number of books."
}
}
class user: Library {
var userName = "Simar"
var userID = "100"
override func profile() -> String {
func printingUserOfLibrary<T>(u:T) {
let user = u as Library
println(u.profile())
}
var user1 = user()
user1.name = "California"
user1.numberOfBooks = 2000
user1.userName = "Vipin"
user1.userID = "101"
println(user1)
output--->>> In California library there are 2000 number of books && this library have Vipin user
class user: Library {
var userName = "Simar"
var userID = "100"
override func profile() -> String {
return "In \(self.name) library there are \(numberOfBooks) number of books && this library have \(self.username) user."
}
}func printingUserOfLibrary<T>(u:T) {
let user = u as Library
println(u.profile())
}
var user1 = user()
user1.name = "California"
user1.numberOfBooks = 2000
user1.userName = "Vipin"
user1.userID = "101"
println(user1)
output--->>> In California library there are 2000 number of books && this library have Vipin user