Reader small image

You're reading from  Learning Swift Second Edition - Second Edition

Product typeBook
Published inMar 2016
Reading LevelBeginner
Publisher
ISBN-139781785887512
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Andrew J Wagner
Andrew J Wagner
author image
Andrew J Wagner

Contacted on 5 Aug 16 Andrew J Wagner is a software developer who concentrates on iOS development and backend web services. He has a degree in computer engineering from Rensselaer Polytechnic Institute, New York. Currently, he works for a development shop based in Denver, CO named Chronos Interactive. He has experience working with and for large-scale companies and small-scale companies as well as running his own contracting and app companies. He is passionate about using computers as a creative outlet and writing software that is beautiful in implementation, functionality, and experience. When he isn't working or spending time with friends and family, he writes for his blog at http://drewag.me. I would like to thank my friends and family for being there for me as support for both my troubles and triumphs. Without their encouragement, I would not have finished this book or achieved any of the other things in my life that make me proud. An especially big thanks to my parents, Fern and Joe, for continually providing me the the tools I need to do the things I love.
Read more about Andrew J Wagner

Right arrow

Chapter 10. Harnessing the Past – Understanding and Translating Objective-C

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:

  • Swift's relationship to Objective-C

  • Background of Objective-C

  • Constants and...

Swift's relationship to Objective-C


As we discussed already, Objective-C was previously the primary language for developing on Apple's platforms. This means that Objective-C had a lot of influence on Swift; the largest of which is that Swift was designed to interoperate with Objective-C. Swift code can call Objective-C code and, likewise, Objective-C code can call Swift code.

Ultimately, Swift was designed, and is still is being designed, to be the next step in programming languages, without having to throw away all of our Objective-C code. Apple's stated goals for the language are for Swift to be more modern, interactive, safe, fast, and powerful. These words would be pretty much meaningless if we didn't already have a baseline to compare Swift against. Since Swift was designed primarily for Apple's platforms, that baseline is largely Objective-C.

Background of Objective-C


Before we can talk about the details of Objective-C, we need to acknowledge its history. Objective-C is based on a language called simply "C". The C programming language was one of the first highly portable languages. Portable means that the same C code could be compiled to run on any processor as long as someone writes a compiler for that platform. Before that, most of the code was written in Assembly; which always had to be written specifically for each processor it would run on.

C is what is commonly referred to as a procedural programming language. It is built on the concept of a series of functions that call each other. It has a very basic support to create your own types, but it has no built in concept of objects. Objective-C was developed as an object-oriented extension to C. Just as Swift is backwards compatible with Objective-C, Objective-C is backwards compatible with C. Really, it simply adds object-oriented features on top of C with some new syntax and...

Constants and variables


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:

var number: Int
int number;

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...

Containers


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.

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:

var array = [Int]()
NSArray *array = [NSArray alloc];
array = [array init];

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...

Control flow


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:

var name = "Sarah"
println("Hello \(name)")
NSString *name = @"Sarah";
NSLog(@"Hello %@", name);

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...

Functions


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...

Types


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.

Structures

In Swift, structures are very similar to classes, but in Objective-C, they are much more different. Structures in Objective-C are essentially just a way of giving a name to a collection of individual types. They cannot contain methods. Even more restrictive than that, structures can't contain Objective-C types. This leaves us with only basic possibilities:

struct Cylinder {
    var radius: Int
    var height: Int
}
var c = Cylinder(radius: 10, height: 10)
typedef struct {
    int radius;
    int height;
} Cylinder;
Cylinder c;
c.radius = 10;
c.height = 5;

Structures in Objective-C start with the keyword typedef, which is short for type definition. This is then followed by the struct keyword and the different components of the structure contained within curly brackets...

Projects


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.

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...

Calling Objective-C code from Swift


The last and possibly the most critical component of understanding Objective-C for our purpose is to be able to call Objective-C code from Swift. This is actually pretty straightforward in most circumstances. We will not take any time to discuss calling Swift code from Objective-C because this book assumes that you are only writing Swift code.

Bridging header

The most important part of being able to call Objective-C code from Swift is how to make the code visible to Swift. As we now know, Objective-C code needs to be imported to be visible to other code. This still holds true with Swift, but Swift has no mechanism to import individual files. Instead, when you add your first Objective-C code to a Swift project, Xcode is going to ask you if you want to add what is called a bridging header:

You should select Yes and then Xcode will automatically create a header file named after the project ending in Bridging-Header.h. This is the file where you need to import...

Using functions


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:

NSArray *addInviteeToListIfSpotAvailable
     (
     NSArray *invitees,
     NSString *newInvitee
     );
addInviteeToListIfSpotAvailable(inviteeList, "Sarah")

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.

Using types

You can use types the same way you use functions. Once the proper header files are imported in the bridging header, you can just use the type as if it were a Swift type:

@interface Contact : NSObject
@property NSString *firstName;
@property NSString *lastName;
- (NSArray *)addToInviteeList:(NSArray *)invitees includeLastName:(BOOL)include;
@end
var contact = Contact()
contact.firstName = "First"
contact.lastName = "Last"
contact.addToInviteeList(inviteeList, includeLastName: false)

Again...

Summary


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...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning Swift Second Edition - Second Edition
Published in: Mar 2016Publisher: ISBN-13: 9781785887512
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Andrew J Wagner

Contacted on 5 Aug 16 Andrew J Wagner is a software developer who concentrates on iOS development and backend web services. He has a degree in computer engineering from Rensselaer Polytechnic Institute, New York. Currently, he works for a development shop based in Denver, CO named Chronos Interactive. He has experience working with and for large-scale companies and small-scale companies as well as running his own contracting and app companies. He is passionate about using computers as a creative outlet and writing software that is beautiful in implementation, functionality, and experience. When he isn't working or spending time with friends and family, he writes for his blog at http://drewag.me. I would like to thank my friends and family for being there for me as support for both my troubles and triumphs. Without their encouragement, I would not have finished this book or achieved any of the other things in my life that make me proud. An especially big thanks to my parents, Fern and Joe, for continually providing me the the tools I need to do the things I love.
Read more about Andrew J Wagner