Organizing your code
Earlier, we wrote an extension for our RestaurantItem
, in which we created a custom init()
method that takes a dictionary object. Extensions are useful for adding your own functionality onto standard libraries, structs, or classes, such as arrays, ints, and strings, or onto your own data types, such as RestaurantItem.
Here is an example. Let's say that you wanted to know the length of a String:
let name = "Craig" name.characters.count
For us to access the count of the String, we would need to access the characters and then get a count.
Let's simplify this by creating an extension:
extension String { var length: Int { return self.characters.count } }
With this newly created String extension, we can now access count by writing the following:
let name = "Craig" name.length
As you can see, extensions are very powerful by adding extra functionality without having to change the main class or struct.
Up until now, we paid very little attention to file structure and more...