Sobes.tech
Junior — Middle

Can you explain the concept of generic types in programming?

sobes.tech AI

Answer from AI

Generic types allow creating components, classes, functions, or structures that work with different data types while ensuring type safety and code reusability.

Instead of writing separate code for each type, you write one generic code with a type parameter. When using this code, you specify the particular type you want to work with.

For example, in Swift (iOS), you can declare a generic function:

generic func swapValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}

var x = 5
var y = 10
swapValues(&x, &y) // x is now 10, y is now 5

var s1 = "hello"
var s2 = "world"
swapValues(&s1, &s2) // s1 is now "world", s2 is now "hello"

Here, T is a type parameter that can be any type. This allows the function to work with any data types while maintaining type safety.

Generic types are widely used to create collections, such as arrays, dictionaries, etc., where the element type can vary.

Can you explain the concept of generic types in… - sobes.tech