What is Generics in Swift
What is Generics?
- Generic enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define.
- Generics are used to avoid duplication and to provide abstraction.
- Generics are type safe, meaning if you pass a string as a generic and try to use as a integer the compiler will complain and you will not be able to compile your code. (This happens because Swift is using Static typing, and is able to give you a compiler error)
- If you use AnyObject the compiler has no idea if the object can be treated as a String or as an Integer. It will allow you to do whatever you want with it.
- 'Arrays' and 'Dictionary' types belong to generic collections. With the help of arrays and dictionaries the arrays are defined to hold 'Int' values and 'String' values or any other types.
- There is just one rule if you want to make your function generic. All you need to do is put
<anything>
right next to a function name.
Example:
func doanything<T>(value: T) {
print(value)
}
doanything(value: 012) // Int
doanything(value: "Pawan") // String
doanything(value: 112.12) // Double
doanything(value: true) // Bool
Thanks for reading, Happy Coding 👨💻