Book Image

Swift: Developing iOS Applications

By : Jon Hoffman, Andrew J Wagner, Giordano Scalzo
Book Image

Swift: Developing iOS Applications

By: Jon Hoffman, Andrew J Wagner, Giordano Scalzo

Overview of this book

The Swift––Developing iOS Applications course will take you on a journey to become an efficient iOS and OS X developer, with the latest trending topic in town. Right from the basics to the advanced level topics, this course would cover everything in detail. We’ll embark our journey by dividing the learning path into four modules. Each of these modules are a mini course in their own right; and as you complete each one, you’ll gain key skills and be ready for the material in the next module. The first module is like a step-by-step guide to programming in Swift 2. Each topic is separated into compressible sections that are full of practical examples and easy-to-understand explanations. Each section builds on the previous topics, so you can develop a proficient and comprehensive understanding of app development in Swift 2. By the end of this module, you’ll have a basic understanding of Swift 2 and its functionalities. The second module will be the an easy-to-follow guide filled with tutorials to show you how to build real-world apps. The difficulty and complexity level increases chapter by chapter. Each chapter is dedicated to build a new app, beginning from a basic and unstyled app through to a full 3D game. The last two chapters show you how to build a complete client-server e-commerce app right from scratch. By the end of these modules, you’ll be able to build well-designed apps, effectively use AutoLayout, develop videogames, and build server apps. The third and the last module of our course will take an example-based approach where each concept covered is supported by example code to not only give you a good understanding of the concept, but also to demonstrate how to properly implement it.
Table of Contents (6 chapters)
4
A. Biblography
5
Index

While Apple's platforms have been around for many years, Swift is still a very new language. Even before the release of the first iPhone, Apple's primary language of choice was Objective-C. This means that there are a vast number of resources in the world for developing on Apple's platforms using Objective-C. There are many amazing tutorials, code libraries, articles, and more, that are written in Objective-C that are still incredibly valuable for a Swift developer.

To take advantage of these resources, you must have at least a basic understanding of Objective-C, so that you can translate the concepts learned in tutorials and articles into Swift, as well as make use of the time tested Objective-C libraries.

In this chapter, we will develop a basic understanding of Objective-C with a focus on how it compares to Swift with the following topics:

Now, we are ready to dive into the basics of the Objective-C language. Objective-C has constants and variables very similar to Swift but they are declared and worked with slightly differently. Let's take a look at declaring a variable in both Swift and Objective-C:

The first line should look familiar, as it is Swift. The Objective-C version doesn't actually look all that different. The important difference is that the type of the variable is declared before the name instead of after. It is also important to note that Objective-C has no concept of type inference. Every time a variable is declared, it must be given a specific type. You will also see that there is a semicolon after the name. This is because every line of code in Objective-C must end with a semicolon. Lastly, you should notice that we have not explicitly declared number as a variable. This is because all information is assumed to be variable in Objective-C unless specified otherwise. To define number as a constant, we will add the const keyword before its type:

Objective-C has value and reference types just like Swift. However, in Objective-C, the difference between them is more conceptual.

Objective-C actually allows you to make any type a reference type by adding an asterisk:

This declares a reference to a number variable, more commonly referred to as a pointer. In a pointer declaration, the asterisk should always come after the type and before the name.

In Objective-C, reference types are actually loosely mixed with the concept of optional in Swift. All reference types are optional because a pointer can always point to nil:

A pointer can also always be tested for nil:

To access the referenced value, you must dereference it:

You can dereference a pointer by adding an asterisk before it.

This is how pointers are similar to optionals in Swift. The difference is that there is no way to declare a non-optional reference type in Objective-C. Every reference type could technically be nil, even if you design it to never actually be nil. This can often add a lot of unnecessary nil checking and means every function you write that accepts a reference type should probably deal with the nil case.

Finally, the other difference between reference types in the two languages is that Objective-C is not very strict when it comes to what type the pointer is referencing. For example, Objective-C won't complain if we create a new double reference that points at the same thing as the int pointer:

Now, we have two variables: number and another; they are pointing at the same value but assuming that they both are of different types. One of them is clearly going to be wrong, but Objective-C will happily try to use the same value as both a double and an int if you try. This is just one bug that Swift makes impossible by design.

So far, all of the Objective-C code we have looked at is actually strict C. We have not used any of the features that Objective-C added onto C. The main thing that Objective-C adds to C is its class system.

Lets take a look at our first actual Objective-C type called NSString compared to the Swift String type:

Just like in Swift, you can create a string instance using double quotes; however, in Objective-C you must put an @ sign before it.

One big thing to remember with the Objective-C class system is that it is not possible to create an instance of a class that is a value type. All instances must be referenced by a reference type. We cannot create a plain NSString. It must always be an NSString* pointer.

Value types

The

Objective-C actually allows you to make any type a reference type by adding an asterisk:

This declares a reference to a number variable, more commonly referred to as a pointer. In a pointer declaration, the asterisk should always come after the type and before the name.

In Objective-C, reference types are actually loosely mixed with the concept of optional in Swift. All reference types are optional because a pointer can always point to nil:

A pointer can also always be tested for nil:

To access the referenced value, you must dereference it:

You can dereference a pointer by adding an asterisk before it.

This is how pointers are similar to optionals in Swift. The difference is that there is no way to declare a non-optional reference type in Objective-C. Every reference type could technically be nil, even if you design it to never actually be nil. This can often add a lot of unnecessary nil checking and means every function you write that accepts a reference type should probably deal with the nil case.

Finally, the other difference between reference types in the two languages is that Objective-C is not very strict when it comes to what type the pointer is referencing. For example, Objective-C won't complain if we create a new double reference that points at the same thing as the int pointer:

Now, we have two variables: number and another; they are pointing at the same value but assuming that they both are of different types. One of them is clearly going to be wrong, but Objective-C will happily try to use the same value as both a double and an int if you try. This is just one bug that Swift makes impossible by design.

So far, all of the Objective-C code we have looked at is actually strict C. We have not used any of the features that Objective-C added onto C. The main thing that Objective-C adds to C is its class system.

Lets take a look at our first actual Objective-C type called NSString compared to the Swift String type:

Just like in Swift, you can create a string instance using double quotes; however, in Objective-C you must put an @ sign before it.

One big thing to remember with the Objective-C class system is that it is not possible to create an instance of a class that is a value type. All instances must be referenced by a reference type. We cannot create a plain NSString. It must always be an NSString* pointer.

Reference types

Objective-C

actually allows you to make any type a reference type by adding an asterisk:

This declares a reference to a number variable, more commonly referred to as a pointer. In a pointer declaration, the asterisk should always come after the type and before the name.

In Objective-C, reference types are actually loosely mixed with the concept of optional in Swift. All reference types are optional because a pointer can always point to nil:

A pointer can also always be tested for nil:

To access the referenced value, you must dereference it:

You can dereference a pointer by adding an asterisk before it.

This is how pointers are similar to optionals in Swift. The difference is that there is no way to declare a non-optional reference type in Objective-C. Every reference type could technically be nil, even if you design it to never actually be nil. This can often add a lot of unnecessary nil checking and means every function you write that accepts a reference type should probably deal with the nil case.

Finally, the other difference between reference types in the two languages is that Objective-C is not very strict when it comes to what type the pointer is referencing. For example, Objective-C won't complain if we create a new double reference that points at the same thing as the int pointer:

Now, we have two variables: number and another; they are pointing at the same value but assuming that they both are of different types. One of them is clearly going to be wrong, but Objective-C will happily try to use the same value as both a double and an int if you try. This is just one bug that Swift makes impossible by design.

So far, all of the Objective-C code we have looked at is actually strict C. We have not used any of the features that Objective-C added onto C. The main thing that Objective-C adds to C is its class system.

Lets take a look at our first actual Objective-C type called NSString compared to the Swift String type:

Just like in Swift, you can create a string instance using double quotes; however, in Objective-C you must put an @ sign before it.

One big thing to remember with the Objective-C class system is that it is not possible to create an instance of a class that is a value type. All instances must be referenced by a reference type. We cannot create a plain NSString. It must always be an NSString* pointer.

Objective-C has the same exact core containers that Swift does, with the two exceptions being that they are named slightly differently, and all of the containers in Objective-C are reference types because of the basic requirement that all Objective-C types must be reference types.

In Objective-C arrays are called NSArray. Let's take a look at the initialization of an array in both Swift and Objective-C side-by-side:

We have defined a variable called array that is a reference to the type NSArray. We then assign it to a newly allocated instance of NSArray. The square bracket notation in Objective-C allows us to call methods on a type or on an instance. Each separate call is always contained within a single set of square brackets. In this case, we are first calling the alloc method on the NSArray class. This returns a newly allocated variable that is of the type NSArray.

In contrast to Swift, Objective-C requires a two-step process to initialize a new instance. First, the memory must be allocated and then it must be initialized. Allocating means that we are reserving the memory for that object and initializing it means that we are setting it to its default value. This is what we are doing in the second line. The second line asks the instance to initialize itself. We reassign the array to the result of the call to init, because it is possible for init to return nil. Note that we are not dereferencing the array variable in order to make a call on it. We actually call the methods directly on the pointer.

Now, it is kind of a waste to use two lines to initialize a new instance, so often the calls are chained together:

This calls alloc on NSArray and then immediately calls on init on the result of that. The array variable is then assigned to the result of the init call. Be aware that it is possible for alloc to return nil, in which case we would be calling init on nil. In Objective-C this is OK; if you call a method on nil, it will simply always return nil. This is similar to how optional chaining works in Swift.

There is also an alternative to calling alloc and init; it's called simply new:

This class method allocates and initializes the instance at the same time. This is great when you are not passing any arguments into init, but you will still need to call alloc separately when you are passing arguments into it. We will see examples of this later on.

You may have noticed that we have not specified what type this array is supposed to hold. This is because it is actually not possible. All arrays in Objective-C can contain any mix of types as long as they are not C types. This means that an NSArray cannot contain an int (there is an NSNumber class instead), but it can contain any mix of NSStrings, NSArrays, or any other Objective-C type. The compiler will not do any form of type checking for you, which means that we can write code expecting the wrong type to be in the array. This is yet another classification of bug that Swift makes impossible.

So how do we add objects to our array? The reality is that the NSArray class does not allow us to add or remove objects from it. In other words, NSArray is immutable. Instead, there is a version of an array called NSMutableArray that allows us to add and remove objects. Then we can use the addObject: method:

Methods in Objective-C and Swift are named in the same way with a colon indicating each argument. In Objective-C, the colon is also used when calling the method to indicate the following code is the value to pass into the method.

The existence of a plain NSArray is to serve the same basic purpose as a constant array in Swift. In fact, we will see that all Objective-C containers are split into mutable and non-mutable versions. A mutable container can be passed into a method and treated like the non-mutable version to add some safety by not allowing unwanted code to modify the array.

Now, to access a value in an NSArray we have two options. The full way is to use the objectAtIndex: method:

We can also use square brackets, similar to Swift:

Note that we are just assuming that the type returned from the array is an NSString. We can just as easily assume that it is another type, say NSArray:

As we know, this will be wrong and will almost certainly cause bugs later in the code but the compiler will not complain.

Lastly, to remove an object from a mutable array, we can use the removeObjectAtIndex: method:

The other important feature that you will need to be aware of is that Objective-C also has array literals, so you don't have to build them up dynamically:

Array literals start with an @ symbol just like a string, but then it is defined by a list of objects within square brackets just like Swift.

There is a lot more that arrays can do, but you should be able to understand what each method does when you see it because most are well named. The methods are also often named the same in each language or you can look them up online, where Apple has extensive documentation. The purpose of this chapter is just to get you comfortable enough to have a high-level understanding of Objective-C code.

Following the same pattern as arrays, dictionaries in Objective-C are called NSDictionary and NSMutableDictionary. A dictionary is initialized in the exact same way as shown:

To set a value, we use the setObject:forKey: method:

Just like with arrays, we cannot set new objects on non-mutable dictionaries. Also, this is our first example of a method that takes more than one argument. As you can see, each argument is contained within the square brackets but separated by a space and the label for that argument. In this pattern, Objective-C methods can have a number of arguments.

Now to access a value we can use the objectForKey: method or square brackets again:

Again, we are assuming that the resulting object being returned is a string, because we know what we just put into the dictionary. This assumption isn't always safe and we also need to always be aware that this method will return nil if an object does not exist for that key.

Lastly, to remove an object, we can use the removeObjectForKey: method:

This is all relatively straightforward, especially when you are reading the code. This verbosity was always a great feature of Objective-C to write understandable code and this was definitely carried forward into Swift.

Dictionaries also have literals, but unlike NSArrays and Swift array literals, dictionary literals in Objective-C are declared using curly brackets. Otherwise, it looks very similar to Swift:

Again, we have to start our literal with an @ symbol. We can also see that we can use numbers as objects in our containers as long as we put an @ symbol before each one. Instead of creating something such as an int type, this creates an NSNumber instance. You shouldn't need to know much about the NSNumber class except that it is a class to represent many different forms of numbers as objects.

Arrays

In

Objective-C arrays are called NSArray. Let's take a look at the initialization of an array in both Swift and Objective-C side-by-side:

We have defined a variable called array that is a reference to the type NSArray. We then assign it to a newly allocated instance of NSArray. The square bracket notation in Objective-C allows us to call methods on a type or on an instance. Each separate call is always contained within a single set of square brackets. In this case, we are first calling the alloc method on the NSArray class. This returns a newly allocated variable that is of the type NSArray.

In contrast to Swift, Objective-C requires a two-step process to initialize a new instance. First, the memory must be allocated and then it must be initialized. Allocating means that we are reserving the memory for that object and initializing it means that we are setting it to its default value. This is what we are doing in the second line. The second line asks the instance to initialize itself. We reassign the array to the result of the call to init, because it is possible for init to return nil. Note that we are not dereferencing the array variable in order to make a call on it. We actually call the methods directly on the pointer.

Now, it is kind of a waste to use two lines to initialize a new instance, so often the calls are chained together:

This calls alloc on NSArray and then immediately calls on init on the result of that. The array variable is then assigned to the result of the init call. Be aware that it is possible for alloc to return nil, in which case we would be calling init on nil. In Objective-C this is OK; if you call a method on nil, it will simply always return nil. This is similar to how optional chaining works in Swift.

There is also an alternative to calling alloc and init; it's called simply new:

This class method allocates and initializes the instance at the same time. This is great when you are not passing any arguments into init, but you will still need to call alloc separately when you are passing arguments into it. We will see examples of this later on.

You may have noticed that we have not specified what type this array is supposed to hold. This is because it is actually not possible. All arrays in Objective-C can contain any mix of types as long as they are not C types. This means that an NSArray cannot contain an int (there is an NSNumber class instead), but it can contain any mix of NSStrings, NSArrays, or any other Objective-C type. The compiler will not do any form of type checking for you, which means that we can write code expecting the wrong type to be in the array. This is yet another classification of bug that Swift makes impossible.

So how do we add objects to our array? The reality is that the NSArray class does not allow us to add or remove objects from it. In other words, NSArray is immutable. Instead, there is a version of an array called NSMutableArray that allows us to add and remove objects. Then we can use the addObject: method:

Methods in Objective-C and Swift are named in the same way with a colon indicating each argument. In Objective-C, the colon is also used when calling the method to indicate the following code is the value to pass into the method.

The existence of a plain NSArray is to serve the same basic purpose as a constant array in Swift. In fact, we will see that all Objective-C containers are split into mutable and non-mutable versions. A mutable container can be passed into a method and treated like the non-mutable version to add some safety by not allowing unwanted code to modify the array.

Now, to access a value in an NSArray we have two options. The full way is to use the objectAtIndex: method:

We can also use square brackets, similar to Swift:

Note that we are just assuming that the type returned from the array is an NSString. We can just as easily assume that it is another type, say NSArray:

As we know, this will be wrong and will almost certainly cause bugs later in the code but the compiler will not complain.

Lastly, to remove an object from a mutable array, we can use the removeObjectAtIndex: method:

The other important feature that you will need to be aware of is that Objective-C also has array literals, so you don't have to build them up dynamically:

Array literals start with an @ symbol just like a string, but then it is defined by a list of objects within square brackets just like Swift.

There is a lot more that arrays can do, but you should be able to understand what each method does when you see it because most are well named. The methods are also often named the same in each language or you can look them up online, where Apple has extensive documentation. The purpose of this chapter is just to get you comfortable enough to have a high-level understanding of Objective-C code.

Following the same pattern as arrays, dictionaries in Objective-C are called NSDictionary and NSMutableDictionary. A dictionary is initialized in the exact same way as shown:

To set a value, we use the setObject:forKey: method:

Just like with arrays, we cannot set new objects on non-mutable dictionaries. Also, this is our first example of a method that takes more than one argument. As you can see, each argument is contained within the square brackets but separated by a space and the label for that argument. In this pattern, Objective-C methods can have a number of arguments.

Now to access a value we can use the objectForKey: method or square brackets again:

Again, we are assuming that the resulting object being returned is a string, because we know what we just put into the dictionary. This assumption isn't always safe and we also need to always be aware that this method will return nil if an object does not exist for that key.

Lastly, to remove an object, we can use the removeObjectForKey: method:

This is all relatively straightforward, especially when you are reading the code. This verbosity was always a great feature of Objective-C to write understandable code and this was definitely carried forward into Swift.

Dictionaries also have literals, but unlike NSArrays and Swift array literals, dictionary literals in Objective-C are declared using curly brackets. Otherwise, it looks very similar to Swift:

Again, we have to start our literal with an @ symbol. We can also see that we can use numbers as objects in our containers as long as we put an @ symbol before each one. Instead of creating something such as an int type, this creates an NSNumber instance. You shouldn't need to know much about the NSNumber class except that it is a class to represent many different forms of numbers as objects.

Dictionaries

Following

the same pattern as arrays, dictionaries in Objective-C are called NSDictionary and NSMutableDictionary. A dictionary is initialized in the exact same way as shown:

To set a value, we use the setObject:forKey: method:

Just like with arrays, we cannot set new objects on non-mutable dictionaries. Also, this is our first example of a method that takes more than one argument. As you can see, each argument is contained within the square brackets but separated by a space and the label for that argument. In this pattern, Objective-C methods can have a number of arguments.

Now to access a value we can use the objectForKey: method or square brackets again:

Again, we are assuming that the resulting object being returned is a string, because we know what we just put into the dictionary. This assumption isn't always safe and we also need to always be aware that this method will return nil if an object does not exist for that key.

Lastly, to remove an object, we can use the removeObjectForKey: method:

This is all relatively straightforward, especially when you are reading the code. This verbosity was always a great feature of Objective-C to write understandable code and this was definitely carried forward into Swift.

Dictionaries also have literals, but unlike NSArrays and Swift array literals, dictionary literals in Objective-C are declared using curly brackets. Otherwise, it looks very similar to Swift:

Again, we have to start our literal with an @ symbol. We can also see that we can use numbers as objects in our containers as long as we put an @ symbol before each one. Instead of creating something such as an int type, this creates an NSNumber instance. You shouldn't need to know much about the NSNumber class except that it is a class to represent many different forms of numbers as objects.

Objective-C has many of the same control flow paradigms as Swift. We will go through each of them quickly, but before we do, let's take a look at the Objective-C equivalent of print:

Instead of print, we are using a function called NSLog. Objective-C does not have string interpolation, so NSLog is a somewhat more complex solution than print. The first argument to NSLog is a string that describes the format to be printed out. This includes a placeholder for each piece of information we want to log that indicates the type it should expect. Every placeholder starts with a percent symbol. In this case, we are using an at-symbol to indicate what we are going to be substituting in a string. Every argument after the initial format will be substituted for the placeholders in the same order they are passed in. Here, this means that it will end up logging Hello Sarah just like the Swift code.

Now, we are ready to look at the different methods of control flow in Objective-C.

Just like conditionals, loops in Objective-C are very similar to Swift. While-loops are identical except that the parentheses are required:

The for-in loops are slightly different, in this you must specify the type of the variable you are looping through with the following:

You may have also noticed that when we are looping through an NSDictionary in Objective-C you only get the key. This is because tuples do not exist in Objective-C. Instead, you must access the value from the original dictionary, using the key as you loop through.

The other feature that is missing from Objective-C is ranges. To loop through a range of numbers, Objective-C programmers must use a different kind of loop called a for loop:

This loop is made up of three parts: an initial value, a condition to run until, and an operation to perform after each loop. This version loops through the numbers 1 to 10 just like the Swift version. Clearly, it is still possible to translate the Swift code into Objective-C; it just isn't as clean.

Even with that limitation, you can see that Objective-C and Swift loops are pretty much the same except for the parentheses requirement.

Conditionals

A

Just like conditionals, loops in Objective-C are very similar to Swift. While-loops are identical except that the parentheses are required:

The for-in loops are slightly different, in this you must specify the type of the variable you are looping through with the following:

You may have also noticed that when we are looping through an NSDictionary in Objective-C you only get the key. This is because tuples do not exist in Objective-C. Instead, you must access the value from the original dictionary, using the key as you loop through.

The other feature that is missing from Objective-C is ranges. To loop through a range of numbers, Objective-C programmers must use a different kind of loop called a for loop:

This loop is made up of three parts: an initial value, a condition to run until, and an operation to perform after each loop. This version loops through the numbers 1 to 10 just like the Swift version. Clearly, it is still possible to translate the Swift code into Objective-C; it just isn't as clean.

Even with that limitation, you can see that Objective-C and Swift loops are pretty much the same except for the parentheses requirement.

Switches

Switches

Just like conditionals, loops in Objective-C are very similar to Swift. While-loops are identical except that the parentheses are required:

The for-in loops are slightly different, in this you must specify the type of the variable you are looping through with the following:

You may have also noticed that when we are looping through an NSDictionary in Objective-C you only get the key. This is because tuples do not exist in Objective-C. Instead, you must access the value from the original dictionary, using the key as you loop through.

The other feature that is missing from Objective-C is ranges. To loop through a range of numbers, Objective-C programmers must use a different kind of loop called a for loop:

This loop is made up of three parts: an initial value, a condition to run until, and an operation to perform after each loop. This version loops through the numbers 1 to 10 just like the Swift version. Clearly, it is still possible to translate the Swift code into Objective-C; it just isn't as clean.

Even with that limitation, you can see that Objective-C and Swift loops are pretty much the same except for the parentheses requirement.

Loops

Just like

conditionals, loops in Objective-C are very similar to Swift. While-loops are identical except that the parentheses are required:

The for-in loops are slightly different, in this you must specify the type of the variable you are looping through with the following:

You may have also noticed that when we are looping through an NSDictionary in Objective-C you only get the key. This is because tuples do not exist in Objective-C. Instead, you must access the value from the original dictionary, using the key as you loop through.

The other feature that is missing from Objective-C is ranges. To loop through a range of numbers, Objective-C programmers must use a different kind of loop called a for loop:

This loop is made up of three parts: an initial value, a condition to run until, and an operation to perform after each loop. This version loops through the numbers 1 to 10 just like the Swift version. Clearly, it is still possible to translate the Swift code into Objective-C; it just isn't as clean.

Even with that limitation, you can see that Objective-C and Swift loops are pretty much the same except for the parentheses requirement.

So far we have called some Objective-C functions but we have not defined any yet. Let's see what the Objective-C versions are of the functions we defined in Chapter 2, Building Blocks – Variables, Collections, and Flow Control.

Our most basic function definition didn't take any arguments and didn't return anything. The Objective-C version looks similar to the following code:

func sayHello() {
    print("Hello World!");
}
sayHello()
void sayHello() {
    NSLog(@"Hello World!");
}
sayHello();

Objective-C functions always starts with the type that the function returns instead of the keyword func. In this case, we aren't actually returning anything, so we use the keyword void to indicate that.

Functions that take arguments and return values have more of a disparity between the two languages:

func addInviteeToListIfSpotAvailable
    (
    invitees: [String],
    newInvitee: String
    )
    -> [String]
{
    if invitees.count >= 20 {
        return invitees
    }
    return invitees + [newInvitee]
}
addInviteeToListIfSpotAvailable(invitees, newInvitee: "Roana")
NSArray *addInviteeToListIfSpotAvailable
    (
    NSArray *invitees,
    NSString *newInvitee
    )
{
    if (invitees.count >= 20) {
        return invitees;
    }
    NSMutableArray *copy = [invitees mutableCopy];
    [copy addObject:newInvitee];
    return copy;
}
addInviteeToListIfSpotAvailable(invitees, @"Roana");

Again, the Objective-C version defines what it is returning at the beginning of the function. Also, just like variables, parameters to functions must have their type defined before their name instead of after. The rest however, is pretty similar: the arguments are contained within parentheses and separated by commas; the code of the function is contained within curly brackets and we use the return keyword to indicate what we want to return.

This specific implementation actually brings up an interesting requirement for dealing with arrays in Objective-C. Just like we want to avoid mutable arrays in Swift, we normally want to avoid them in Objective-C. In this case, we still don't want to modify the passed in array, we just want to add the new invitee to the end of a copied version. In Swift, because arrays are value types, the copy is made for us and we can use the addition operator to add on the new invitee. In Objective-C, we need to explicitly make a copy of the array. More than that, we need the copy to be mutable so that we can add the new invitee to it.

All in all, the biggest difference between Swift functions and Objective-C methods is the definition of the return value being at the beginning or the end of the parameters. The memory is handled in the same way in both languages. When passing in a pointer in Objective-C, the pointer itself is copied but both versions are going to reference the exact same instance. When a value type is passed into a function in Swift, the value is simply copied and the two versions have nothing to do with each other after that.

The type system in Objective-C is a little bit more disparate than Swift. This is because the structures and enumerations in Objective-C come from C. Only classes and categories come from the Objective-C extension.

Enumerations are also much more restrictive in Objective-C. They are really just a simple mechanism to represent a finite list of related possible values. This allows us to still represent possible primary colors:

Just like with structures, Objective-C enumerations start with the keyword typedef followed by enum with the name at the end of the definition. Each case is contained within the curly brackets and separated by a comma.

Notice that every case of the enumeration starts with the name of the enumeration. This is a very common convention, to make it easy for code completion and to show all possible values of an enumeration. This is because in Objective-C, you cannot specify a specific enumeration value through the name of the enumeration itself. Instead, every case is its own keyword. This is why when we are assigning our color variable to blue; we use the case name by itself.

Enumerations in Objective-C cannot have methods, associated values, or represent any other values except for integers. In fact, in Objective-C enumerations, every case has a numeric value. If you don't specify any, they start at 0 and go up by 1 for each case. If you want, you can manually specify a value for one or more of the cases:

Each case after a manually specified case will continue to increase by one. This means that in the preceding code PrimaryColorRed is still 0 but PrimaryColorBlue is 11.

Unlike Objective-C structures and enumerations, classes are very similar to their Swift counterparts. Objective-C classes can contain methods and properties, use inheritance, and get initialized. However, they look pretty different. Most notably, a class in Objective-C is split into two parts: its interface and its implementation. The interface is intended to be the public interface to the class, while the implementation includes the implementation of that interface in addition to any other private methods.

Let's start by looking again at our contact class from Chapter 3, One Piece at a Time – Types, Scopes, and Projects and what it looks like in Objective-C:

class Contact {
    var firstName: String = "First"
    var lastName: String = "Last"
}
@interface Contact : NSObject {
    NSString *firstName;
    NSString *lastName;
}
@end

@implementation Contact
@end

Already Objective-C is taking a lot more lines of code. First, we have the interface declaration. This begins with the @interface keyword and ends with the @end keyword. Within the square brackets is a list of attributes. These are essentially the same as the attributes of a structure, except that you can include Objective-C objects in the attributes. These attributes are not commonly written like this because using the properties will create these automatically, as we will see later.

You will also notice that our class is inheriting from a class called NSObject, as indicated by : NSObject. This is because every class in Objective-C must inherit from NSObject, which makes NSObject the most basic form of class. However, don't let the term "basic" fool you; NSObject provides a lot of functionality. We won't really get into that here, but you should at least be aware of it.

The other part of the class is the implementation. It starts with the @implementation keyword followed by the name of the class we are implementing and then ends again with the @end keyword. Here, we have not actually added any extra functionality to our contact class. However, you may notice that our class is missing something that the Swift version has.

Objective-C does not allow specifying default values for any attributes or properties. This means that we have to implement an initializer that sets the default values:

In Objective-C, initializers are the exact same as a method, except that by convention they start with the name init. This is actually just a convention but it is important, as it will cause problems down the line with memory management and interacting with the code from Swift.

The minus sign at the beginning indicates that this is a method. Next, the return type is specified within parentheses, which is then followed by the name of the method: in this case init. The body of the method is contained in curly brackets just like a function.

The return type for all initializers is going to be id by convention. This allows us to easily override initializers of subclasses.

Virtually all initializers will follow this same pattern. Just like in Swift, self references the instance that this method is being called on. The first line assigns the self reference to the result by calling the superclass's initializer with [super init]. We then allow for the possibility that the initializer fails and returns nil by testing it for nil in the if (self) statement. The if statement will fail if self is nil. If it is not nil, we assign the default values. Finally, we return self, so that calling code can maintain a reference to the newly initialized object. However, this is just a convention and Objective-C does not have any protection around properly initializing properties.

The Objective-C version of the contact class still isn't exactly like the Swift version because the firstName and lastName attributes are not accessible from outside the class. To make them accessible we need to define them as public properties and we can drop them from being explicit attributes:

Note that the properties are defined outside of the curly brackets but still within the @interface. In fact, you can leave off the curly brackets altogether if you have nothing to define in it. Properties automatically generate attributes by the same name except with an underscore at the beginning:

Alternatively, you can just set the values using self:

There are nuances to each approach but for just general reading purposes, it doesn't matter which one is used.

Also, just as you can define weak references in Swift, you can do so in Objective-C:

If you want, you can replace weak with strong, but just like Swift, all properties are strong by default. Weak references in Objective-C will automatically be set to nil if the referenced object gets deallocated. You can also use the unsafe_unretained keyword, which is equivalent to unowned in Swift. However, this is rarely used as the only difference between the two in Objective-C is that unsafe_unretained does not reset the value to nil; instead, it will reference an invalid object if the object gets deallocated causing confusing crashes if used.

In addition to weak or strong, you can also specify that a property is readonly or readwrite:

Each property attribute should be written inside the parentheses separated by a comma. As the readonly name implies, this makes it so that the property can be read but not written to. Every property is read-write by default, so normally it is not necessary to include it.

Note that you may also see the keyword nonatomic in the parentheses. This is a more advanced topic that is beyond the scope of this book.

Categories in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Structures

In Swift, structures

Enumerations are also much more restrictive in Objective-C. They are really just a simple mechanism to represent a finite list of related possible values. This allows us to still represent possible primary colors:

Just like with structures, Objective-C enumerations start with the keyword typedef followed by enum with the name at the end of the definition. Each case is contained within the curly brackets and separated by a comma.

Notice that every case of the enumeration starts with the name of the enumeration. This is a very common convention, to make it easy for code completion and to show all possible values of an enumeration. This is because in Objective-C, you cannot specify a specific enumeration value through the name of the enumeration itself. Instead, every case is its own keyword. This is why when we are assigning our color variable to blue; we use the case name by itself.

Enumerations in Objective-C cannot have methods, associated values, or represent any other values except for integers. In fact, in Objective-C enumerations, every case has a numeric value. If you don't specify any, they start at 0 and go up by 1 for each case. If you want, you can manually specify a value for one or more of the cases:

Each case after a manually specified case will continue to increase by one. This means that in the preceding code PrimaryColorRed is still 0 but PrimaryColorBlue is 11.

Unlike Objective-C structures and enumerations, classes are very similar to their Swift counterparts. Objective-C classes can contain methods and properties, use inheritance, and get initialized. However, they look pretty different. Most notably, a class in Objective-C is split into two parts: its interface and its implementation. The interface is intended to be the public interface to the class, while the implementation includes the implementation of that interface in addition to any other private methods.

Let's start by looking again at our contact class from Chapter 3, One Piece at a Time – Types, Scopes, and Projects and what it looks like in Objective-C:

class Contact {
    var firstName: String = "First"
    var lastName: String = "Last"
}
@interface Contact : NSObject {
    NSString *firstName;
    NSString *lastName;
}
@end

@implementation Contact
@end

Already Objective-C is taking a lot more lines of code. First, we have the interface declaration. This begins with the @interface keyword and ends with the @end keyword. Within the square brackets is a list of attributes. These are essentially the same as the attributes of a structure, except that you can include Objective-C objects in the attributes. These attributes are not commonly written like this because using the properties will create these automatically, as we will see later.

You will also notice that our class is inheriting from a class called NSObject, as indicated by : NSObject. This is because every class in Objective-C must inherit from NSObject, which makes NSObject the most basic form of class. However, don't let the term "basic" fool you; NSObject provides a lot of functionality. We won't really get into that here, but you should at least be aware of it.

The other part of the class is the implementation. It starts with the @implementation keyword followed by the name of the class we are implementing and then ends again with the @end keyword. Here, we have not actually added any extra functionality to our contact class. However, you may notice that our class is missing something that the Swift version has.

Objective-C does not allow specifying default values for any attributes or properties. This means that we have to implement an initializer that sets the default values:

In Objective-C, initializers are the exact same as a method, except that by convention they start with the name init. This is actually just a convention but it is important, as it will cause problems down the line with memory management and interacting with the code from Swift.

The minus sign at the beginning indicates that this is a method. Next, the return type is specified within parentheses, which is then followed by the name of the method: in this case init. The body of the method is contained in curly brackets just like a function.

The return type for all initializers is going to be id by convention. This allows us to easily override initializers of subclasses.

Virtually all initializers will follow this same pattern. Just like in Swift, self references the instance that this method is being called on. The first line assigns the self reference to the result by calling the superclass's initializer with [super init]. We then allow for the possibility that the initializer fails and returns nil by testing it for nil in the if (self) statement. The if statement will fail if self is nil. If it is not nil, we assign the default values. Finally, we return self, so that calling code can maintain a reference to the newly initialized object. However, this is just a convention and Objective-C does not have any protection around properly initializing properties.

The Objective-C version of the contact class still isn't exactly like the Swift version because the firstName and lastName attributes are not accessible from outside the class. To make them accessible we need to define them as public properties and we can drop them from being explicit attributes:

Note that the properties are defined outside of the curly brackets but still within the @interface. In fact, you can leave off the curly brackets altogether if you have nothing to define in it. Properties automatically generate attributes by the same name except with an underscore at the beginning:

Alternatively, you can just set the values using self:

There are nuances to each approach but for just general reading purposes, it doesn't matter which one is used.

Also, just as you can define weak references in Swift, you can do so in Objective-C:

If you want, you can replace weak with strong, but just like Swift, all properties are strong by default. Weak references in Objective-C will automatically be set to nil if the referenced object gets deallocated. You can also use the unsafe_unretained keyword, which is equivalent to unowned in Swift. However, this is rarely used as the only difference between the two in Objective-C is that unsafe_unretained does not reset the value to nil; instead, it will reference an invalid object if the object gets deallocated causing confusing crashes if used.

In addition to weak or strong, you can also specify that a property is readonly or readwrite:

Each property attribute should be written inside the parentheses separated by a comma. As the readonly name implies, this makes it so that the property can be read but not written to. Every property is read-write by default, so normally it is not necessary to include it.

Note that you may also see the keyword nonatomic in the parentheses. This is a more advanced topic that is beyond the scope of this book.

Categories in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Enumerations

Enumerations

are also much more restrictive in Objective-C. They are really just a simple mechanism to represent a finite list of related possible values. This allows us to still represent possible primary colors:

Just like with structures, Objective-C enumerations start with the keyword typedef followed by enum with the name at the end of the definition. Each case is contained within the curly brackets and separated by a comma.

Notice that every case of the enumeration starts with the name of the enumeration. This is a very common convention, to make it easy for code completion and to show all possible values of an enumeration. This is because in Objective-C, you cannot specify a specific enumeration value through the name of the enumeration itself. Instead, every case is its own keyword. This is why when we are assigning our color variable to blue; we use the case name by itself.

Enumerations in Objective-C cannot have methods, associated values, or represent any other values except for integers. In fact, in Objective-C enumerations, every case has a numeric value. If you don't specify any, they start at 0 and go up by 1 for each case. If you want, you can manually specify a value for one or more of the cases:

Each case after a manually specified case will continue to increase by one. This means that in the preceding code PrimaryColorRed is still 0 but PrimaryColorBlue is 11.

Unlike Objective-C structures and enumerations, classes are very similar to their Swift counterparts. Objective-C classes can contain methods and properties, use inheritance, and get initialized. However, they look pretty different. Most notably, a class in Objective-C is split into two parts: its interface and its implementation. The interface is intended to be the public interface to the class, while the implementation includes the implementation of that interface in addition to any other private methods.

Let's start by looking again at our contact class from Chapter 3, One Piece at a Time – Types, Scopes, and Projects and what it looks like in Objective-C:

class Contact {
    var firstName: String = "First"
    var lastName: String = "Last"
}
@interface Contact : NSObject {
    NSString *firstName;
    NSString *lastName;
}
@end

@implementation Contact
@end

Already Objective-C is taking a lot more lines of code. First, we have the interface declaration. This begins with the @interface keyword and ends with the @end keyword. Within the square brackets is a list of attributes. These are essentially the same as the attributes of a structure, except that you can include Objective-C objects in the attributes. These attributes are not commonly written like this because using the properties will create these automatically, as we will see later.

You will also notice that our class is inheriting from a class called NSObject, as indicated by : NSObject. This is because every class in Objective-C must inherit from NSObject, which makes NSObject the most basic form of class. However, don't let the term "basic" fool you; NSObject provides a lot of functionality. We won't really get into that here, but you should at least be aware of it.

The other part of the class is the implementation. It starts with the @implementation keyword followed by the name of the class we are implementing and then ends again with the @end keyword. Here, we have not actually added any extra functionality to our contact class. However, you may notice that our class is missing something that the Swift version has.

Objective-C does not allow specifying default values for any attributes or properties. This means that we have to implement an initializer that sets the default values:

In Objective-C, initializers are the exact same as a method, except that by convention they start with the name init. This is actually just a convention but it is important, as it will cause problems down the line with memory management and interacting with the code from Swift.

The minus sign at the beginning indicates that this is a method. Next, the return type is specified within parentheses, which is then followed by the name of the method: in this case init. The body of the method is contained in curly brackets just like a function.

The return type for all initializers is going to be id by convention. This allows us to easily override initializers of subclasses.

Virtually all initializers will follow this same pattern. Just like in Swift, self references the instance that this method is being called on. The first line assigns the self reference to the result by calling the superclass's initializer with [super init]. We then allow for the possibility that the initializer fails and returns nil by testing it for nil in the if (self) statement. The if statement will fail if self is nil. If it is not nil, we assign the default values. Finally, we return self, so that calling code can maintain a reference to the newly initialized object. However, this is just a convention and Objective-C does not have any protection around properly initializing properties.

The Objective-C version of the contact class still isn't exactly like the Swift version because the firstName and lastName attributes are not accessible from outside the class. To make them accessible we need to define them as public properties and we can drop them from being explicit attributes:

Note that the properties are defined outside of the curly brackets but still within the @interface. In fact, you can leave off the curly brackets altogether if you have nothing to define in it. Properties automatically generate attributes by the same name except with an underscore at the beginning:

Alternatively, you can just set the values using self:

There are nuances to each approach but for just general reading purposes, it doesn't matter which one is used.

Also, just as you can define weak references in Swift, you can do so in Objective-C:

If you want, you can replace weak with strong, but just like Swift, all properties are strong by default. Weak references in Objective-C will automatically be set to nil if the referenced object gets deallocated. You can also use the unsafe_unretained keyword, which is equivalent to unowned in Swift. However, this is rarely used as the only difference between the two in Objective-C is that unsafe_unretained does not reset the value to nil; instead, it will reference an invalid object if the object gets deallocated causing confusing crashes if used.

In addition to weak or strong, you can also specify that a property is readonly or readwrite:

Each property attribute should be written inside the parentheses separated by a comma. As the readonly name implies, this makes it so that the property can be read but not written to. Every property is read-write by default, so normally it is not necessary to include it.

Note that you may also see the keyword nonatomic in the parentheses. This is a more advanced topic that is beyond the scope of this book.

Categories in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Classes

Unlike

Objective-C structures and enumerations, classes are very similar to their Swift counterparts. Objective-C classes can contain methods and properties, use inheritance, and get initialized. However, they look pretty different. Most notably, a class in Objective-C is split into two parts: its interface and its implementation. The interface is intended to be the public interface to the class, while the implementation includes the implementation of that interface in addition to any other private methods.

Let's start by looking again at our contact class from Chapter 3, One Piece at a Time – Types, Scopes, and Projects and what it looks like in Objective-C:

class Contact {
    var firstName: String = "First"
    var lastName: String = "Last"
}
@interface Contact : NSObject {
    NSString *firstName;
    NSString *lastName;
}
@end

@implementation Contact
@end

Already Objective-C is taking a lot more lines of code. First, we have the interface declaration. This begins with the @interface keyword and ends with the @end keyword. Within the square brackets is a list of attributes. These are essentially the same as the attributes of a structure, except that you can include Objective-C objects in the attributes. These attributes are not commonly written like this because using the properties will create these automatically, as we will see later.

You will also notice that our class is inheriting from a class called NSObject, as indicated by : NSObject. This is because every class in Objective-C must inherit from NSObject, which makes NSObject the most basic form of class. However, don't let the term "basic" fool you; NSObject provides a lot of functionality. We won't really get into that here, but you should at least be aware of it.

The other part of the class is the implementation. It starts with the @implementation keyword followed by the name of the class we are implementing and then ends again with the @end keyword. Here, we have not actually added any extra functionality to our contact class. However, you may notice that our class is missing something that the Swift version has.

Objective-C does not allow specifying default values for any attributes or properties. This means that we have to implement an initializer that sets the default values:

In Objective-C, initializers are the exact same as a method, except that by convention they start with the name init. This is actually just a convention but it is important, as it will cause problems down the line with memory management and interacting with the code from Swift.

The minus sign at the beginning indicates that this is a method. Next, the return type is specified within parentheses, which is then followed by the name of the method: in this case init. The body of the method is contained in curly brackets just like a function.

The return type for all initializers is going to be id by convention. This allows us to easily override initializers of subclasses.

Virtually all initializers will follow this same pattern. Just like in Swift, self references the instance that this method is being called on. The first line assigns the self reference to the result by calling the superclass's initializer with [super init]. We then allow for the possibility that the initializer fails and returns nil by testing it for nil in the if (self) statement. The if statement will fail if self is nil. If it is not nil, we assign the default values. Finally, we return self, so that calling code can maintain a reference to the newly initialized object. However, this is just a convention and Objective-C does not have any protection around properly initializing properties.

The Objective-C version of the contact class still isn't exactly like the Swift version because the firstName and lastName attributes are not accessible from outside the class. To make them accessible we need to define them as public properties and we can drop them from being explicit attributes:

Note that the properties are defined outside of the curly brackets but still within the @interface. In fact, you can leave off the curly brackets altogether if you have nothing to define in it. Properties automatically generate attributes by the same name except with an underscore at the beginning:

Alternatively, you can just set the values using self:

There are nuances to each approach but for just general reading purposes, it doesn't matter which one is used.

Also, just as you can define weak references in Swift, you can do so in Objective-C:

If you want, you can replace weak with strong, but just like Swift, all properties are strong by default. Weak references in Objective-C will automatically be set to nil if the referenced object gets deallocated. You can also use the unsafe_unretained keyword, which is equivalent to unowned in Swift. However, this is rarely used as the only difference between the two in Objective-C is that unsafe_unretained does not reset the value to nil; instead, it will reference an invalid object if the object gets deallocated causing confusing crashes if used.

In addition to weak or strong, you can also specify that a property is readonly or readwrite:

Each property attribute should be written inside the parentheses separated by a comma. As the readonly name implies, this makes it so that the property can be read but not written to. Every property is read-write by default, so normally it is not necessary to include it.

Note that you may also see the keyword nonatomic in the parentheses. This is a more advanced topic that is beyond the scope of this book.

Categories in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Basic class

Let's start

by looking again at our contact class from Chapter 3, One Piece at a Time – Types, Scopes, and Projects and what it looks like in Objective-C:

class Contact {
    var firstName: String = "First"
    var lastName: String = "Last"
}
@interface Contact : NSObject {
    NSString *firstName;
    NSString *lastName;
}
@end

@implementation Contact
@end

Already Objective-C is taking a lot more lines of code. First, we have the interface declaration. This begins with the @interface keyword and ends with the @end keyword. Within the square brackets is a list of attributes. These are essentially the same as the attributes of a structure, except that you can include Objective-C objects in the attributes. These attributes are not commonly written like this because using the properties will create these automatically, as we will see later.

You will also notice that our class is inheriting from a class called NSObject, as indicated by : NSObject. This is because every class in Objective-C must inherit from NSObject, which makes NSObject the most basic form of class. However, don't let the term "basic" fool you; NSObject provides a lot of functionality. We won't really get into that here, but you should at least be aware of it.

The other part of the class is the implementation. It starts with the @implementation keyword followed by the name of the class we are implementing and then ends again with the @end keyword. Here, we have not actually added any extra functionality to our contact class. However, you may notice that our class is missing something that the Swift version has.

Objective-C does not allow specifying default values for any attributes or properties. This means that we have to implement an initializer that sets the default values:

In Objective-C, initializers are the exact same as a method, except that by convention they start with the name init. This is actually just a convention but it is important, as it will cause problems down the line with memory management and interacting with the code from Swift.

The minus sign at the beginning indicates that this is a method. Next, the return type is specified within parentheses, which is then followed by the name of the method: in this case init. The body of the method is contained in curly brackets just like a function.

The return type for all initializers is going to be id by convention. This allows us to easily override initializers of subclasses.

Virtually all initializers will follow this same pattern. Just like in Swift, self references the instance that this method is being called on. The first line assigns the self reference to the result by calling the superclass's initializer with [super init]. We then allow for the possibility that the initializer fails and returns nil by testing it for nil in the if (self) statement. The if statement will fail if self is nil. If it is not nil, we assign the default values. Finally, we return self, so that calling code can maintain a reference to the newly initialized object. However, this is just a convention and Objective-C does not have any protection around properly initializing properties.

The Objective-C version of the contact class still isn't exactly like the Swift version because the firstName and lastName attributes are not accessible from outside the class. To make them accessible we need to define them as public properties and we can drop them from being explicit attributes:

Note that the properties are defined outside of the curly brackets but still within the @interface. In fact, you can leave off the curly brackets altogether if you have nothing to define in it. Properties automatically generate attributes by the same name except with an underscore at the beginning:

Alternatively, you can just set the values using self:

There are nuances to each approach but for just general reading purposes, it doesn't matter which one is used.

Also, just as you can define weak references in Swift, you can do so in Objective-C:

If you want, you can replace weak with strong, but just like Swift, all properties are strong by default. Weak references in Objective-C will automatically be set to nil if the referenced object gets deallocated. You can also use the unsafe_unretained keyword, which is equivalent to unowned in Swift. However, this is rarely used as the only difference between the two in Objective-C is that unsafe_unretained does not reset the value to nil; instead, it will reference an invalid object if the object gets deallocated causing confusing crashes if used.

In addition to weak or strong, you can also specify that a property is readonly or readwrite:

Each property attribute should be written inside the parentheses separated by a comma. As the readonly name implies, this makes it so that the property can be read but not written to. Every property is read-write by default, so normally it is not necessary to include it.

Note that you may also see the keyword nonatomic in the parentheses. This is a more advanced topic that is beyond the scope of this book.

Categories in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Initializers

Objective-C does

not allow specifying default values for any attributes or properties. This means that we have to implement an initializer that sets the default values:

In Objective-C, initializers are the exact same as a method, except that by convention they start with the name init. This is actually just a convention but it is important, as it will cause problems down the line with memory management and interacting with the code from Swift.

The minus sign at the beginning indicates that this is a method. Next, the return type is specified within parentheses, which is then followed by the name of the method: in this case init. The body of the method is contained in curly brackets just like a function.

The return type for all initializers is going to be id by convention. This allows us to easily override initializers of subclasses.

Virtually all initializers will follow this same pattern. Just like in Swift, self references the instance that this method is being called on. The first line assigns the self reference to the result by calling the superclass's initializer with [super init]. We then allow for the possibility that the initializer fails and returns nil by testing it for nil in the if (self) statement. The if statement will fail if self is nil. If it is not nil, we assign the default values. Finally, we return self, so that calling code can maintain a reference to the newly initialized object. However, this is just a convention and Objective-C does not have any protection around properly initializing properties.

The Objective-C version of the contact class still isn't exactly like the Swift version because the firstName and lastName attributes are not accessible from outside the class. To make them accessible we need to define them as public properties and we can drop them from being explicit attributes:

Note that the properties are defined outside of the curly brackets but still within the @interface. In fact, you can leave off the curly brackets altogether if you have nothing to define in it. Properties automatically generate attributes by the same name except with an underscore at the beginning:

Alternatively, you can just set the values using self:

There are nuances to each approach but for just general reading purposes, it doesn't matter which one is used.

Also, just as you can define weak references in Swift, you can do so in Objective-C:

If you want, you can replace weak with strong, but just like Swift, all properties are strong by default. Weak references in Objective-C will automatically be set to nil if the referenced object gets deallocated. You can also use the unsafe_unretained keyword, which is equivalent to unowned in Swift. However, this is rarely used as the only difference between the two in Objective-C is that unsafe_unretained does not reset the value to nil; instead, it will reference an invalid object if the object gets deallocated causing confusing crashes if used.

In addition to weak or strong, you can also specify that a property is readonly or readwrite:

Each property attribute should be written inside the parentheses separated by a comma. As the readonly name implies, this makes it so that the property can be read but not written to. Every property is read-write by default, so normally it is not necessary to include it.

Note that you may also see the keyword nonatomic in the parentheses. This is a more advanced topic that is beyond the scope of this book.

Categories in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Properties

The

Objective-C version of the contact class still isn't exactly like the Swift version because the firstName and lastName attributes are not accessible from outside the class. To make them accessible we need to define them as public properties and we can drop them from being explicit attributes:

Note that the properties are defined outside of the curly brackets but still within the @interface. In fact, you can leave off the curly brackets altogether if you have nothing to define in it. Properties automatically generate attributes by the same name except with an underscore at the beginning:

Alternatively, you can just set the values using self:

There are nuances to each approach but for just general reading purposes, it doesn't matter which one is used.

Also, just as you can define weak references in Swift, you can do so in Objective-C:

If you want, you can replace weak with strong, but just like Swift, all properties are strong by default. Weak references in Objective-C will automatically be set to nil if the referenced object gets deallocated. You can also use the unsafe_unretained keyword, which is equivalent to unowned in Swift. However, this is rarely used as the only difference between the two in Objective-C is that unsafe_unretained does not reset the value to nil; instead, it will reference an invalid object if the object gets deallocated causing confusing crashes if used.

In addition to weak or strong, you can also specify that a property is readonly or readwrite:

Each property attribute should be written inside the parentheses separated by a comma. As the readonly name implies, this makes it so that the property can be read but not written to. Every property is read-write by default, so normally it is not necessary to include it.

Note that you may also see the keyword nonatomic in the parentheses. This is a more advanced topic that is beyond the scope of this book.

Categories in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Methods

We

Categories in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Inheritance

Just as

Categories in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Categories

Categories

in Objective-C are just like Swift extensions. They allow you to add new methods to existing classes. They look very similar to plain classes:

We know that this is a category instead of a normal class because we added a name within parentheses after the class name. Every category on a class must have a unique name. In this case, we are calling it Helpers and we are adding a method to return the contact's full name.

Here, for the first time, we are declaring a method inside the interface. This is also possible with classes. A method definition looks exactly like an implementation except that it ends in a semicolon instead of the code inside the curly brackets. This will allow us to call the method from outside the current file, as we will see in more detail in the upcoming projects section.

Categories can also add properties, but you will have to define your own getter and setter methods because just like Swift extensions can't add stored properties, Objective-C categories can't add attributes:

These types of properties are very similar to calculated properties. If you need to allow reading from a property, you must implement a method with the exact same name that takes no parameters and returns the same type. If you want to be able to write to the property you will have to implement a method that starts with set, followed by the same property name with a capital first letter, that takes the property type as a parameter and returns nothing. This allows outside classes to interact with the property as if it were an attribute, when in fact it is just another set of methods. Again, this is possible within a class or a category.

Like Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Protocols

Like

Swift, Objective-C has the idea of protocols. Their definition looks similar to this:

Here, we are using the @protocol keyword instead of @interface and it still ends with the @end keyword. We can define any properties or methods that we want. We can then say that a class implements the protocol similar to this:

The list of protocols that a class implements should be listed within angled brackets after the class it inherits from separated by commas. In this case we are only implementing a single protocol so we don't need any commas. This code also declares a contents property, so that we can implement the protocol as shown:

Note that we don't do anything special in the implementation to implement a protocol; we just need to make sure the proper methods and computed properties are implemented.

The other thing you should be aware of is that protocols in Objective-C are not used in the same way as classes. You can't just define a variable to be a protocol; instead, you must give it a type and require that it implement the protocol. Most commonly, this is done with the id type:

Any variable declaration can require that it not only inherits from a specific type, but also implements certain protocols.

Lastly, blocks are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Blocks

Lastly, blocks

are the Objective-C alternative to closures in Swift. They are actually a late addition to Objective-C so their syntax is somewhat complex:

Let's break this down. We start like any other variable with the variable's name and type before the equals sign. The name starts with a carrot symbol (^) inside the first set of parentheses. In this case, we are calling it doubleClosure. The actual type of the closure surrounds that. The type it starts with is the type the closure returns, which in this case is an int. The second set of parentheses lists the types of the parameters the closure accepts. In total, this means that we are defining a closure called doubleClosure that accepts int and returns int.

Then, we move on to the business of implementing the closure. All closure implementations start with a carrot symbol followed by any arguments in parentheses and curly brackets with the actual implementation. Once a closure is defined, it can be called similar to any other function. However, you should always be aware that it is possible for a closure to be nil, in which calling it will cause the program to crash.

It is also possible to define a function or method that accepts a closure as a parameter. First, a function:

Note that the type id signifies any Objective-C object and even though it doesn't have an asterisk, it is a reference type. The usage above looks exactly like a standalone block usage. However, the syntax looks somewhat different in a method:

This is because a method's parameter name is separated by parentheses. This causes the name of the parameter to be moved from being with the carrot to after the parentheses. In the end, we can say that the nuances of the syntax aren't too important when reading Objective-C code and translating to Swift, as long as you recognize that a carrot symbol indicates a block. Many Objective-C programmers look up the syntax of a block on a regular basis.

All of the same memory concerns exist in Objective-C with blocks. By default, all arguments are captured strongly and the syntax to capture them weakly is much more convoluted. Instead of including the weak captures in the block itself, you must create weak variables outside of the block and use them:

Here we use the keyword __weak (that has two underscores) to indicate that the weakBall variable should only have a weak reference to ball. We can then safely reference the weakBall variable within the block and not create a circular reference.

Now that we have a pretty good understanding of Objective-C, let's discuss what Objective-C code looks like in a project. Unlike the Swift code, Objective-C is written in two different types of files. One of the types is called a header file and ends in the extension h. The other type is called an implementation file and ends in the extension m.

Before we can really discuss what the difference is between the two, we first have to discuss code exposure. In Swift, all the code you write is accessible to all other code in your project. This is not true with Objective-C. In Objective-C, you must explicitly indicate that you want to have access to the code in another file.

The header files are the types of files that can be included by other files. This means that header files should only contain the interfaces of types. In fact, this is why the separation exists between class interfaces and implementations. Any file can import a header file and that essentially inserts all the code of one file into the file that is importing it:

This allows us to separate each class into its own file just as we like to do in Swift. The danger is that we must only put code that can be safely imported into headers. If you try to put implementations in a header, you will end up with duplicate implementations for every time you import the header.

In the preceding example, we actually imported one header file into another. This means that if a different file now includes this header file, it will essentially be importing both header files.

You will also notice that there are two different ways to import a file. We import foundation with angled brackets and imported our car header with quotes. Angled brackets are used for importing header files from frameworks, while quotes are used for importing header files within the same framework or application.

A lot of the time it isn't actually necessary for one header file to include another because all it needs to know about is the existence of the class. If it doesn't need to know any actual details about the class, it can simply indicate that the class exists using the @class keyword:

Now, the compiler will not complain that it doesn't know what Car is. However, you will most likely still need to import the car header in the implementation file because you will probably be interacting with some part of that class.

As you might have guessed, implementation files are generally for the implementation of your types. These files are not imported into others; they simply fulfill the promises of what the interface files have defined. This means that header and implementation files generally exist in pairs. If you are defining a steering wheel class, you will most likely create a SteeringWheel.h header and a SteeringWheel.m implementation file. Any other code that needs to interact with the details of the steering wheel class will import the header and at compile time, the compiler will make all of the implementations available to the running program.

Implementation files are also a great place to hide private code, because they cannot be imported by other code. Since the code is not visible anywhere else, it is unlikely to be interacted with. This means that people will sometimes add class interfaces to implementation files if their use is localized to just that file. It is also very common to add what is called an anonymous category to an implementation file:

This is considered anonymous because the category was not actually given a name. This means there is no way to pair an implementation directly with that category. Instead, the implementation should be defined within the normal implementation of the class. This provides a great way to define any private properties and methods at the top of an implementation file. You don't technically need to define any private methods because as long as they are implemented in the same file, they can be interacted with. However, it is often nice to have a concise list of the available properties and methods at the top of the file.

This brings up another point, that only methods that you intend to use from outside files should be declared in the header. You should always consider a header to be the public interface of your class and it should be as minimal as possible. It is always written from the perspective of outside files. This is the way that Objective-C implements access control. It isn't formally built into the language but the compiler will warn you if you try to interact with code that has not been imported. It is actually still possible to interact with these private interfaces, especially if you duplicate the interface declaration somewhere else, but it is considered best practice to not do that and Apple will actually reject your apps during review if you try to interact with private parts of their API.

Header files

The header files

are the types of files that can be included by other files. This means that header files should only contain the interfaces of types. In fact, this is why the separation exists between class interfaces and implementations. Any file can import a header file and that essentially inserts all the code of one file into the file that is importing it:

This allows us to separate each class into its own file just as we like to do in Swift. The danger is that we must only put code that can be safely imported into headers. If you try to put implementations in a header, you will end up with duplicate implementations for every time you import the header.

In the preceding example, we actually imported one header file into another. This means that if a different file now includes this header file, it will essentially be importing both header files.

You will also notice that there are two different ways to import a file. We import foundation with angled brackets and imported our car header with quotes. Angled brackets are used for importing header files from frameworks, while quotes are used for importing header files within the same framework or application.

A lot of the time it isn't actually necessary for one header file to include another because all it needs to know about is the existence of the class. If it doesn't need to know any actual details about the class, it can simply indicate that the class exists using the @class keyword:

Now, the compiler will not complain that it doesn't know what Car is. However, you will most likely still need to import the car header in the implementation file because you will probably be interacting with some part of that class.

As you might have guessed, implementation files are generally for the implementation of your types. These files are not imported into others; they simply fulfill the promises of what the interface files have defined. This means that header and implementation files generally exist in pairs. If you are defining a steering wheel class, you will most likely create a SteeringWheel.h header and a SteeringWheel.m implementation file. Any other code that needs to interact with the details of the steering wheel class will import the header and at compile time, the compiler will make all of the implementations available to the running program.

Implementation files are also a great place to hide private code, because they cannot be imported by other code. Since the code is not visible anywhere else, it is unlikely to be interacted with. This means that people will sometimes add class interfaces to implementation files if their use is localized to just that file. It is also very common to add what is called an anonymous category to an implementation file:

This is considered anonymous because the category was not actually given a name. This means there is no way to pair an implementation directly with that category. Instead, the implementation should be defined within the normal implementation of the class. This provides a great way to define any private properties and methods at the top of an implementation file. You don't technically need to define any private methods because as long as they are implemented in the same file, they can be interacted with. However, it is often nice to have a concise list of the available properties and methods at the top of the file.

This brings up another point, that only methods that you intend to use from outside files should be declared in the header. You should always consider a header to be the public interface of your class and it should be as minimal as possible. It is always written from the perspective of outside files. This is the way that Objective-C implements access control. It isn't formally built into the language but the compiler will warn you if you try to interact with code that has not been imported. It is actually still possible to interact with these private interfaces, especially if you duplicate the interface declaration somewhere else, but it is considered best practice to not do that and Apple will actually reject your apps during review if you try to interact with private parts of their API.

Implementation files

As you

might have guessed, implementation files are generally for the implementation of your types. These files are not imported into others; they simply fulfill the promises of what the interface files have defined. This means that header and implementation files generally exist in pairs. If you are defining a steering wheel class, you will most likely create a SteeringWheel.h header and a SteeringWheel.m implementation file. Any other code that needs to interact with the details of the steering wheel class will import the header and at compile time, the compiler will make all of the implementations available to the running program.

Implementation files are also a great place to hide private code, because they cannot be imported by other code. Since the code is not visible anywhere else, it is unlikely to be interacted with. This means that people will sometimes add class interfaces to implementation files if their use is localized to just that file. It is also very common to add what is called an anonymous category to an implementation file:

This is considered anonymous because the category was not actually given a name. This means there is no way to pair an implementation directly with that category. Instead, the implementation should be defined within the normal implementation of the class. This provides a great way to define any private properties and methods at the top of an implementation file. You don't technically need to define any private methods because as long as they are implemented in the same file, they can be interacted with. However, it is often nice to have a concise list of the available properties and methods at the top of the file.

This brings up another point, that only methods that you intend to use from outside files should be declared in the header. You should always consider a header to be the public interface of your class and it should be as minimal as possible. It is always written from the perspective of outside files. This is the way that Objective-C implements access control. It isn't formally built into the language but the compiler will warn you if you try to interact with code that has not been imported. It is actually still possible to interact with these private interfaces, especially if you duplicate the interface declaration somewhere else, but it is considered best practice to not do that and Apple will actually reject your apps during review if you try to interact with private parts of their API.

Organization

Other Bridging header

The

After you have exposed the headers to Swift, it is very simple to call functions. You can simply call the functions directly as if they didn't have parameter names:

Xcode will even autocomplete the code for you. From your Swift files point of view, there is no way to know if that function is implemented in Objective-C or Swift.

You will note that this acts as a pattern when Objective-C types are translated to Swift. Any reference type is going to be translated, by default, to an implicitly unwrapped optional because of the nature of Objective-C reference types. The compiler can't automatically know if the value returned could be nil or not, so it doesn't know if it should be translated as a regular optional or a non-optional. However, Objective-C developers can add annotations to let the compiler know if a value can be nil or not.

Using types

You can

You will note that this acts as a pattern when Objective-C types are translated to Swift. Any reference type is going to be translated, by default, to an implicitly unwrapped optional because of the nature of Objective-C reference types. The compiler can't automatically know if the value returned could be nil or not, so it doesn't know if it should be translated as a regular optional or a non-optional. However, Objective-C developers can add annotations to let the compiler know if a value can be nil or not.

Containers

You may

You will note that this acts as a pattern when Objective-C types are translated to Swift. Any reference type is going to be translated, by default, to an implicitly unwrapped optional because of the nature of Objective-C reference types. The compiler can't automatically know if the value returned could be nil or not, so it doesn't know if it should be translated as a regular optional or a non-optional. However, Objective-C developers can add annotations to let the compiler know if a value can be nil or not.

Annotations

You will

note that this acts as a pattern when Objective-C types are translated to Swift. Any reference type is going to be translated, by default, to an implicitly unwrapped optional because of the nature of Objective-C reference types. The compiler can't automatically know if the value returned could be nil or not, so it doesn't know if it should be translated as a regular optional or a non-optional. However, Objective-C developers can add annotations to let the compiler know if a value can be nil or not.

Nullability

The first Container element types

Objective-C developer

While Swift is the hot new language right now in the Apple development community, there is no immediate sign that Objective-C is getting replaced fully. All of Apple's APIs are still written in Objective-C and it would be a lot of work for Apple to rewrite them, if they even wanted to. Apple definitely designed Swift to be able to live alongside Objective-C, so for now we have to assume that Objective-C is here to stay. This makes understanding and being able to interact with Objective-C very valuable, even as a Swift developer.

In this chapter, we have gotten an overview of the most pertinent Objective-C features and syntax from the point of view of a primarily Swift developer. We have learned how Swift is basically a part of a long line of evolving languages. It was heavily influenced by Apple's desire to make it backwards compatible with Objective-C and Objective-C was actually an evolution of C which was an evolution of Assembly and so on. Objective-C is still a powerful language with the ability to express many of the same concepts as Swift. Objective-C has similar concepts of constants and variables with more of a stress on variables. It also has the same basic containers but control flow is slightly different in the two languages. Swift has more powerful switches and ranges, but the underlying concepts are still very much the same. Functions are almost identical between the two languages but the type system in Objective-C is somewhat more limited because it can only express classes unlike Swift which has a powerful concept of classes, structures, and enumerations. Structures and enumerations still exist in Objective-C, but they really come directly from C and can do a lot less. Finally, we saw that organizing Objective-C in a project is very much the same and calling Objective-C code from Swift is actually quite straightforward.

There is some debate in the Apple developer community about how relevant Objective-C will be moving forward. There are people that have jumped into Swift development full time and there are others that are waiting for Swift to mature even more before they commit energy to truly learning it. However, there is little debate over the fact that Objective-C knowledge is still going to be relevant for a while, most notably because of the vast resources that exist and the fact that all existing Apple APIs are written in Objective-C. We will put those APIs to use in our next chapter: Chapter 11, A Whole New World – Developing an App, when we will finally dive into some real app development.