Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Learning Swift
  • Table Of Contents Toc
  • Feedback & Rating feedback
Learning Swift

Learning Swift

By : Andrew J Wagner
4.8 (5)
close
close
Learning Swift

Learning Swift

4.8 (5)
By: Andrew J Wagner

Overview of this book

If you are looking to build iOS or OS X apps using the most modern technology, this book is ideal for you. You will find this book especially useful if you are new to programming or if you have yet to develop for iOS or OS X.
Table of Contents (13 chapters)
close
close
12
Index

Defining a generic


A generic is very similar to a type alias. The difference is that the exact type of a generic is determined by the context in which it is used, instead of the implementing types. This also means that a generic only has a single implementation that must support all of the possible types. Let's start by defining a generic function.

The generic function

In Chapter 5, A Modern Paradigm – Closures and Functional Programming, we created a function that helped us find the first number in an array of numbers that passes a test:

func firstInNumbers(
    numbers: [Int],
    passingTest: (number: Int) -> Bool
    ) -> Int?
{
    for number in numbers {
        if passingTest(number: number) {
            return number
        }
    }
    return nil
}

This would be great if we only ever deal with arrays of the Int types, but clearly, it would be helpful if we are able to do this with other types. In fact, I dare say, it would be helpful for all types. We can achieve this very simply...

Unlock full access

Continue reading for free

A Packt free trial gives you instant online access to our library of over 7000 practical eBooks and videos, constantly updated with the latest in tech
bookmark search playlist font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY