Chapter 6. Swift and Cocoa Touch
In this chapter we will have a look at what’s new in Swift 4 and Cocoa Touch, such as the addition of built-in JSON parsing mechanisms. You’ll see how you can utilize these new features to make your code even more robust and easier to read.
6.1 Extending Typed Arrays
Problem
You have some homogeneous arrays (containing objects of the same type) and you want to add a property or a function to arrays of that particular type, without affecting other arrays.
Solution
Create an extension on Array that applies only when the Element of that array is equal to your specific type. For instance, if you want to add a property to all arrays that contain Int instances, and you want the return value of this property to be the largest integer in the array, you can extend an array of integers as follows:
extensionArraywhereElement==Int{varlargestInteger:Element?{returnsorted().last}}
Now you can use this property on arrays of integers, as shown here:
letnumbers=[10,20,1,4,9](numbers.largestInteger??0)
Discussion
Swift now has the ability to extend collections of specific element types. For instance, imagine that you have the following structure:
structPerson{letname:Stringletage:Int}
You can then create an array of Person as shown here:
letpersons=[Person(name:"Foo",age:22),Person(name:"Bar",age:30),Person(name:"Baz",age:19)]
If you wanted to find the youngest Person instance this array traditionally, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access