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:

extension Array where Element == Int{

  var largestInteger: Element?{
    return sorted().last
  }

}

Now you can use this property on arrays of integers, as shown here:

let numbers = [10, 20, 1, 4, 9]
print(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:

struct Person{
  let name: String
  let age: Int
}

You can then create an array of Person as shown here:

let persons = [
  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, ...

Get iOS 11 Swift Programming Cookbook 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.