DEV Community

Cover image for Swift pro tip of the day: Extension with generic where clause
Eleazar Estrella
Eleazar Estrella

Posted on • Edited on

17 4

Swift pro tip of the day: Extension with generic where clause

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:

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

Source: The Swift Programming Language

The most common sample could be to make a ViewController comfort a protocol using extensions:

extension MyViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath)
return cell
}
}

Generic type:

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.

Source: The Swift Programming Language

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:

var total: Double {
get {
//Please take into consideration that this can be done by using swift's reduce function as well
//var x = pieces.reduce(0.0) { (result, piece) -> Double in
// return result + piece.price
//}
var x = 0.0
pieces.forEach { piece in
if piece.selected { x+=piece.price }
}
return x
}
}

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:

extension Array where Element == Piece {
var totalPrice: Double {
var x = 0.0
self.forEach { piece in
if piece.selected { x+=piece.price}
}
return x
}
}
let pieces = [Piece]()
let stringArray = [String]()
print(pieces.totalPrice) //prints the total price of selected pieces
print(stringArray.totalPrice) //throws Value of type '[String]' has no member 'totalPrice'

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!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
viktorstrate profile image
Viktor Strate Kløvedal

Is there a way to add the following constraint on Array.Element with a generic parameter T?

extension Array where Element == Set<T>
Enter fullscreen mode Exit fullscreen mode

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post