Junior
Mis on genrikud programmeerimises?
sobes.tech AI
Vastus AI-lt
Generics are a way to write flexible, reusable code that works with any data types while maintaining type safety. They allow deferring the specification of a specific type until the point of use.
Main advantages:
- Avoiding code duplication: You can write one algorithm/data structure that works with different types.
- Type safety: The compiler checks type conformity during compilation, preventing runtime errors related to incorrect types.
- More expressive code: Clearly shows the developer's intentions regarding data types.
Example in Swift:
Generic Stack structure:
struct Stack<Element> {
// generic Element is used as the type of array elements
private var items: [Element] = []
// generic Element is used as the type of parameter
mutating func push(_ item: Element) {
items.append(item)
}
// generic Element is used as the return type
mutating func pop() -> Element {
return items.removeLast()
}
}
Using with strings:
var stringStack = Stack<String>()
stringStack.push("hello")
stringStack.push("world")
let lastString = stringStack.pop() // lastString is of type String
Using with numbers:
var intStack = Stack<Int>()
intStack.push(1)
intStack.push(2)
let lastInt = intStack.pop() // lastInt is of type Int
Without generics, separate structures would need to be written for Stack<String>, Stack<Int>, etc., or less safe approaches (like Any) would have to be used.