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

Extending the existing generics


The two main generics we probably want to extend are arrays and dictionaries. These are the two most prominent containers provided by Swift and they are used in virtually every app. Extending a generic type is simple once you understand that an extension itself does not need to be generic.

Enhancing arrays

Knowing that an array is declared as the struct Array<T>, your first instinct is probably to extend an array that might look something like this:

extension Array<T> { // error: Generic arguments are not allowed on an extension
   // ...
}

However, as you can see, you would get an error. Instead, you can simply leave out the placeholder specification and still use the T placeholder inside your implementations. Your other instinct might be to declare T as a placeholder for your individual methods:

extension Array {
    func someMethod<T>() {
        // ...
    }
}

This is more dangerous because the compiler doesn't give an error. This is wrong...

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