CODEX

Swift: Generics Made Simple

Avoid code duplication by writing functions and types that work with all types using generics.

Artturi Jalli
Mar 5 · 3 min read
Photo by Luca Bravo on Unsplash

Generics in Swift

What Are Generics in Swift

What Problem Do Generics Solve

func infoString(_ a: String){
print("Argument type is String with a value of \(a)")
}
func infoInt(_ a: Int){
print("Argument type is Int with a value of \(a)")
}
func infoDouble(_ a: Double){
print("Argument type is Double with a value of \(a)")
}
// ... and so on
func info<T>(_ a: T){
print("Argument type is \(type(of: a)) with a value of \(a)")
}
info(3) // Argument type is Int with a value of 3
info(3.2) // Argument type is Double with a value of 3.2
info("Yeah") // Argument type is String with a value of Yeah

Another Example of Generics

let numbers = [1, 2, 3, 4, 5]
let names = ["Nicolas", "Anne", "Robert", "Sofie"]
func printInts(_ arr: [Int]){
arr.forEach { print($0) }
}
func printStrings(_ arr: [String]){
arr.forEach { print($0) }
}
printInts(numbers) // prints all the numbers
printStrings(names) // prints all the names
func arrPrint<T>(_ arr: [T]) {
arr.forEach { print($0) }
}
// A test that it really works:arrPrint(numbers) // prints all the numbers
arrPrint(names) // prints all the names

Conclusion

That’s it!

CodeX

Everything connected with Tech & Code

Artturi Jalli

Written by

Tech Expert, Entrepreneur, Software Engineer from Finland. Writing about programming and science. Check out my blog at https://www.codingem.com/

CodeX

CodeX

Everything connected with Tech & Code

Artturi Jalli

Written by

Tech Expert, Entrepreneur, Software Engineer from Finland. Writing about programming and science. Check out my blog at https://www.codingem.com/

CodeX

CodeX

Everything connected with Tech & Code

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store