Created
August 7, 2021 05:36
-
-
Save JarvisTheAvenger/d637846885878618e04e124ed7053da3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// Generics | |
/* Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner. | |
*/ | |
// Normal function | |
func add(first: Int, second: Int) -> Int { | |
return first + second | |
} | |
add(first: 1, second: 2) | |
//Generic function | |
func add<T: Numeric>(first: T, second: T) -> T { | |
return first + second | |
} | |
add(first: 4.2, second: 2) | |
// Generic Types - Class | |
class User<T: Numeric> { | |
func addSomething(first: T, second: T) -> T { | |
return first + second | |
} | |
} | |
let user = User<Int>() | |
user.addSomething(first: 2, second: 3) | |
let user1 = User<Float>() | |
user1.addSomething(first: 4.2, second: 3.5) | |
// Generic Types - Protocols | |
protocol Doable { | |
associatedtype T | |
var work : T { get set } | |
func doSomething() | |
} | |
class Factory: Doable { | |
typealias T = String | |
var work: String | |
init(_ workName: String) { | |
self.work = workName | |
} | |
func doSomething() { | |
print(work) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment