Junior
What programming principle allows the use of generics?
sobes.tech AI
Answer from AI
Subtype polymorphism.
Generics in Swift implement parametric polymorphism, allowing you to write code that can work with different types without knowing them in advance, but requiring these types to conform to certain constraints (e.g., protocols).
Example of using generics:
// Defining a generic function that takes two parameters of type T,
// where T must conform to the Equatable protocol.
func areEqual<T: Equatable>(_ a: T, _ b: T) -> Bool {
return a == b
}
// Using the generic function with Int
let intResult = areEqual(5, 5) // true
// Using the generic function with String
let stringResult = areEqual("hello", "world") // false
Example of a generic structure (array):
// Defining a generic structure "Stack" that can hold elements of any type T.
struct Stack<T> {
private var elements: [T] = []
mutating func push(_ element: T) {
elements.append(element)
}
mutating func pop() -> T? {
return elements.popLast()
}
}
// Using the generic structure with Int
var intStack = Stack<Int>()
intStack.push(1)
intStack.push(2)
let poppedInt = intStack.pop() // 2
// Using the generic structure with String
var stringStack = Stack<String>()
stringStack.push("A")
stringStack.push("B")
let poppedString = stringStack.pop() // "B"
Advantages of using generics:
- Type safety: The compiler checks types at compile time, reducing runtime errors.
- Code reuse: The same code can work with different types.
- Performance: No need for type casting at runtime.
- Abstraction: Allows abstraction from specific data types.