Generics in Swift allow you to write flexible, reusable, and type-safe code by enabling you to define functions, classes, structures, and enumerations that work with any type.
Example of Generics
func swapValues<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
var x = 10
var y = 20
swapValues(&x, &y)
print(x, y) // Output: 20, 10
var str1 = "Hello"
var str2 = "World"
swapValues(&str1, &str2)
print(str1, str2) // Output: World, Hello
Generic Function Example
func printValue<T>(_ value: T) {
print("The value is: \(value)")
}
//Passing an Integer
printValue(42)
// Output: The value is: 42
//Passing a String
printValue("Hello, Swift!")
// Output: The value is: Hello, Swift!
//Passing a Double
printValue(3.14)
// Output: The value is: 3.14
//Passing a Boolean
printValue(true)
// Output: The value is: true
Explaination
- Generic Type Placeholder:
- The
T
in<T>
is a placeholder for any type. Swift replacesT
with the actual type passed when the function is called.
- The
- Type Safety:
- Even though the function works with any type, Swift ensures type safety at compile time.
- Reusability:
- Instead of writing separate functions for
Int
,String
,Double
, etc., we can write one generic function that works for all types.
- Instead of writing separate functions for
Generic Typealias
typealias StringDictionary<T> = Dictionary<String, T>
var scores: StringDictionary<Int> = ["Bishal": 90, "Ram": 85]
print(scores["Bishal"]!) // Output: 90
Generics and Closures
func performOperation<T>(_ value: T, operation: (T) -> Void) {
operation(value)
}
performOperation(10) { value in
print("Value is \(value)")
}
// Output: Value is 10
Generic Addition Function for Numeric Types
func add<T: AdditiveArithmetic>(_ a: T, _ b: T) -> T {
return a + b
}
//Adding Integers
let intResult = add(10, 20)
print("Sum of Integers: \(intResult)")
// Output: Sum of Integers: 30
//Adding Doubles
let doubleResult = add(3.14, 2.71)
print("Sum of Doubles: \(doubleResult)")
// Output: Sum of Doubles: 5.85
//Adding Floats
let floatResult = add(1.5, 2.5)
print("Sum of Floats: \(floatResult)")
// Output: Sum of Floats: 4.0
Generic Function With Array Elements
func printArrayElements<T>(array: [T]) {
for element in array {
print(element)
}
}
let intArray = [1, 2, 3, 4, 5]
let stringArray = ["Swift", "Generics", "Array"]
let doubleArray = [3.14, 2.71, 1.62]
printArrayElements(array: intArray)
// Output: 1 2 3 4 5
printArrayElements(array: stringArray)
// Output: Swift Generics Array
printArrayElements(array: doubleArray)
// Output: 3.14 2.71 1.62