Inspired by how successful was my previous post a few days ago, I'm writing a continuation with a better approach and in which I can introduce Swift features that are just as interesting as computed properties: extensions and generics, and besides you'll notice how these two converge in a majestic combination. First of all let's quickly define what these two features are:
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the source code (known as retroactive modeling).
Extensions in Swift can:
- Add computed instance properties and computed type properties
- Define instance methods and type methods
- Provide new initializers
- Define subscripts
- Define and use new nested types
- Make an existing type conform to a protocol
The most common sample could be to make a ViewController comfort a protocol using extensions:
Generic code enables you to write flexible, reusable functions, and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.
In addition to generic functions, Swift enables you to define your own generic types. These are custom classes, structures, and enumerations that can work with any type, in a similar way to Array and Dictionary.
Keep in mind that Arrays and Dictionaries are using Generic Types because that's going to be useful later. Do you remember the problem I was facing in my previous post? Let's recapitulate: I need the sum of selected pieces prices within a group of data. The approach I implemented with computed properties was like this:
There is another way to solve this problem using extensions and the generic where clause. You can make an Array extension that requires the element to be a specific type or to conform to a protocol. So the above problem -using this combination- can be solved in the following way:
With the Where Clause, we're specifying that we want the Array Element to be type of Piece and then we are able to add a new property with the necessary logic. Same problem, solved from two different approaches taking advantage of Swift. I hope you enjoyed the post and if so, please follow me because more content will come soon. Goodbye!