Typealias
Introduction
Welcome to the last lesson of The Swift Fundamentals. You’ve come a long way. You will learn how to create fake names for anything. This lesson should be nice and short.
Problem
The parameters are unreadable and boring
Typealias: A false or assumed identity. - Oxford Dictionary
Typealias for String
Instead of using String, let us create a fake name for String.
1. typealias Name = String
3. func insertName(name: Name) {}
4. insertName(name: "Bob Lee")
Typealias for Custom Class
1. class Employee {}
3. typealias MyEmployees = [Employee]
4. func listEmployees(enterEmployees: MyEmployees) {}
Typealias for Tuple
1. typealias GridPoint = (Int, Int)
3. func enterPoint(grid: GridPoint) {
4. print("You've entered, \(grid.0) and \(grid.1)")
5. }
7. enterPoint(grid: (4, 2))
Type Definition
Let’s review how to initialize Array, Dictionary, and Optional.
Array Type
1. let arrayOne: Array<String> = ["Bob", "Bobby"] // Generic Struct
2. let arrayTwo: [String] = ["Bob", "Bobby"]
Dictionary Type
1. let dictTwo: Dictionary<String, Int> = ["Alex": 31, "Paul": 39] // Generic Struct
2. let dictOne: [String: Int] = ["Alex": 31, "Paul": 39]
Optional Type
1. var optionalOne: String?
2. var optionalTwo: Optional<String> // Generic Enum
You will learn more about
optionalsin Chapter 8: Advanced Enums.
Source Code
Conclusion
That’s it. You’ve learned how fake.
