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 ...

Get iOS 10 Programming for Beginners now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.