Welcome back to CodeYourCraft! Today, we're diving into a fascinating topic: Generic Types in Swift. Let's get started! 📝
Generic types are a powerful feature in Swift that allows us to create reusable code by defining functions, classes, and structs without specifying the data type they'll work with. We'll learn how to create and use generic types in this lesson, and we'll even create some practical examples to help you understand the concept better.
Generic types help us write flexible code that can work with different data types without having to rewrite it every time. This makes our code more efficient and easier to maintain. Let's dive into the details!
First, let's create a simple generic function called printArray(). This function will print the elements of an array without specifying its data type.
func printArray<T>(array: Array<T>) {
for item in array {
print(item)
}
}In the above code, T is a placeholder for the data type of the array. The <T> part is called a type constraint, and it tells Swift that the function can work with any data type.
Now, let's use this function with different data types:
var intArray: Array<Int> = [1, 2, 3, 4, 5]
var stringArray: Array<String> = ["apple", "banana", "cherry"]
printArray(array: intArray)
printArray(array: stringArray)We can also create generic structs and classes in Swift. Here's an example of a simple generic struct called Box<T>:
struct Box<T> {
var contents: T
}Now, let's create and use a Box with different data types:
var boxInt = Box<Int>(contents: 10)
var boxString = Box<String>(contents: "Hello")
print(boxInt.contents)
print(boxString.contents)Let's create a generic stack that can work with any data type. We'll add and remove items from the stack using the push() and pop() methods:
struct GenericStack<T> {
private var items: [T] = []
mutating func push(_ item: T) {
items.append(item)
}
mutating func pop() -> T? {
if items.isEmpty { return nil }
let item = items.last
items.removeLast()
return item
}
}Now, let's use our generic stack with different data types:
var myStack = GenericStack<Int>()
myStack.push(10)
myStack.push(20)
myStack.push(30)
print(myStack.pop()!)
print(myStack.pop()!)
print(myStack.pop()!)
myStack.push("FortyTwo")
print(myStack.pop()!) // Output: 30
print(myStack.pop()!) // Output: FortyTwoWhat does `T` represent in generic functions, structs, and classes in Swift?
That's it for today's lesson on generic types in Swift! In the next lesson, we'll dive deeper into more advanced topics like extensions and protocols. Stay tuned! 🎯