Swift Tutorial Part 2: Types and Operations

Welcome to the second part of this learning Swift mini-series, where you’ll learn to use strings, type conversion, type inference and tuples. By Lorenzo Boaro.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

A Peek Behind the Curtains: Protocols

Even though there are a dozen different numeric types, they are pretty easy to understand and use. This is because they all roughly support the same operations. In other words, once you know how to use an Int, using any one of the flavors is very straightforward.

One of the truly great features of Swift is how it formalizes the idea of type commonality using what are called protocols. By learning a protocol, you instantly understand how an entire family of types that use that protocol work.

In the case of integers, the functionality can be diagrammed like so:

Integer Protocols

The arrows indicate conformance to (sometimes called adoption of) a protocol. While this graph does not show all of the protocols that integer types conform to, it gives you insight into how things are organized.

Swift is the first protocol-based language. As you begin to understand the protocols that underly the types, you can start leveraging the system in ways not possible with other languages.

Where to Go From Here?

You can download the final playground using the Download Materials button at the top or bottom of this tutorial. To improve your Swift skills, you will find some mini-exercises to complete. If you are stuck or you need some help, feel free to take advantage of companion solutions.

In this tutorial, you’ve learned that types are a fundamental part of programming. They’re what allow you to correctly store your data. You’ve seen a few more here, including strings and tuples, as well as a bunch of numeric types.

In the next part, you’ll learn about Boolean logic and simple control flow. Head on to Part 3: Flow Control to carry on with this series.

If have any questions or comments, please tell us in the discussion below!

swift-apprentice

This tutorial was taken from Chapter 3 of Swift Apprentice, Fourth Edition, available from the raywenderlich.com store.

Check it out and let us know what you think!