Ad space (banner)
๐ŸฆSwift Lessons
Lesson 51 / 68

Writing Generic Functions

In this lesson you will learn how to write generic functions in Swift, so one function can work with several types. This is for anyone searching for "Swift generics how to use".

Generics (<T>) let you write a function that works with any type instead of committing to one. That is useful when you want the same logic for numbers and for strings.

The sample code defines func larger<T: Comparable>(_ a: T, _ b: T) -> T, so both the numeric larger(3, 7) and the string larger("apple", "banana") go through the same function. The Comparable constraint is what restricts it to comparable types.

A common stumbling block for beginners is why the constraint is needed at all. Adding a constraint to the type parameter raises safety; with a bare T and no constraint, there is no guarantee that comparison operators are available.

In real-world development, generics are widely used to raise reusability and save writing the same method again for every type.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)