0
0
Swiftprogramming~5 mins

Generic type declaration in Swift

Choose your learning style9 modes available
Introduction

Generics let you write flexible code that works with any type. This helps you avoid repeating similar code for different data types.

When you want a function to work with different types of data without rewriting it.
When creating a container like a box or list that can hold any type of item.
When you want to make your code safer by specifying the type it works with.
When you want to reuse code for different data types easily.
Syntax
Swift
struct Box<T> {
    var item: T
}

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

The <T> is a placeholder for any type you use later.

You can use any letter or name inside the angle brackets, but T is common.

Examples
A simple container that can hold any type of value.
Swift
struct Container<T> {
    var value: T
}
A function that prints any type of item.
Swift
func printItem<T>(_ item: T) {
    print("Item: \(item)")
}
A class that holds two values of possibly different types.
Swift
class Pair<A, B> {
    var first: A
    var second: B
    init(_ first: A, _ second: B) {
        self.first = first
        self.second = second
    }
}
Sample Program

This program shows a generic struct Box that can hold any type. It also has a generic function swapValues that swaps two values of the same type. We create boxes for an integer and a string, then swap two integers.

Swift
struct Box<T> {
    var item: T
}

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

var intBox = Box(item: 10)
var stringBox = Box(item: "Hello")

print("Before swap: intBox.item = \(intBox.item), stringBox.item = \(stringBox.item)")

var a = 5
var b = 8
swapValues(&a, &b)
print("After swap: a = \(a), b = \(b)")
OutputSuccess
Important Notes

Generics help keep your code clean and reusable.

Swift checks types at compile time to prevent errors when using generics.

Summary

Generics let you write code that works with any type.

Use angle brackets <> to declare generic types.

They make your code safer and easier to reuse.