|
Published:
February 13, 2015

Swift For Dummies

Overview

Brimming with expert advice and easy-to-follow instructions, Swift For Dummies shows new and existing programmers how to quickly port existing Objective-C applications into Swift and get into the swing of the new language like a pro. Designed from the ground up to be a simpler programming language, it's never been easier to get started creating apps for the iPhone or iPad, or applications for Mac OS X. Inside the book, you'll find out how to set up Xcode for a new Swift application, use operators, objects, and data types, and control program flow with conditional statements. You'll also get the scoop on creating new functions, statements, and declarations, learn useful patterns in an object-oriented environment, and take advantage of frameworks to speed your coding along.

Read More

About The Author

Jesse Feiler is a developer, consultant, and author specializing in Apple technologies. He is the creator of Minutes Machine for iPad, the meeting management app, and Saranac River Trail and is heard regularly on WAMC Public Radio for the Northeast’s The Roundtable.

Sample Chapters

swift for dummies

CHEAT SHEET

Swift is Apple’s programming language for developers to use with iOS and OS X devices.Swift has been designed both to work alongside its predecessor, Objective-C, and to one day be Objective-C’s replacement. When you develop apps for iOS or OS X, you use the Xcode development tool (technically an Integrated Development Environment, or IDE), the Cocoa or Cocoa Touch frameworks, and a programming language —either Objective-C or Swift.

HAVE THIS BOOK?

Articles from
the book

If you are an experienced Objective-C developer, this list reminds you of some features you may be used to that aren’t available in Swift. In each case, workarounds and strategies for replacing your old tried-and-true Objective-C friends are provided. And don’t worry: In most cases, you’ll end up writing less code, and your code will be more robust.
Considering that Swift is a newly developed, object‐oriented language, and that C was developed almost half a century ago (by Dennis Ritchie in 1969–1973), when the object‐oriented paradigm wasn’t even in widespread use, you might think that comparing these two languages would be difficult and, in many ways, unfair to both languages.
Objective‐C dates back to the 1980s — quite a long time ago by computer technology standards. In the decades since its first release, Objective‐C’s influence on programming language technologies and best practices (along with hardware and operating system changes) has demonstrated that the Objective‐C design is robust and flexible.
This is a list of tips, typos, and gotchas from switching between Objective-C and Swift. It doesn't take long to make the transition, but it’s easy to get stuck on this: Types follow variable and constant names: Double myDouble in Objective-C, but myDouble: Double in Swift. Type casting uses function syntax not type syntax: (Double*)myDouble in Objective-C but Double(myDouble) in Swift.
Constants and variables have to be initialized before use in Swift. However, there’s more than one way to do this and get on with your code. If you’re not sure whether your approach will work, test out your initialization strategies in a playground. Here’s how: Create a new playground with a single declaration, like this one: var x Try using your variable, x, in some way, like this: x = x + 2 In this case, you’ll get an error.
Any of the major types (classes, structures, and enumerations) can adopt protocols. You can create a protocol that is adopted by any of them, or you can specify that it is adoptable only by a class. Here are examples of conforming to the basic protocol (MyProtocol). Conforming a class to a protocol Many of the protocols used in the Cocoa and Cocoa Touch frameworks are adopted by classes in the frameworks in part because in Objective‐C, protocols are typically used only with classes.
There are cases where you need to mix and match code between the Objective-C and Swift languages. When it comes to the frameworks, the engineers at Apple are working through the interfaces to provide Swift interfaces alongside the Objective-C versions so that you can use either one to get to the framework in your own app.
Xcode has Interface Builder built into it so that you can design your interface graphically. The key to making it all work is to connect the graphical elements from Interface Builder to your Swift files. Xcode makes it easy — just follow these steps: Open Main.storyboard. Your main storyboard may have a different name; this is the default name.
A bundle identifies your target — that is, the app that you’re building in Swift. That’s the basic definition. The bundle identifier is constructed automatically by Xcode from your organization identifier and your product identifier. The combination of the two should be unique, and it will be if you use the reverse domain name of your company or organization as the organization name.
When you're thinking about creating an app, how do you decide how to implement its functionality? Swift, along with the Cocoa and Cocoa Touch frameworks, provides a wide variety of tools to assist you. Here’s a list of some of the questions to ask yourself when deciding which one(s) to use: Is this something that people need to be able to do both on iOS and OS X?
Putting classes, structures, and enumerations together reflects their common features in Swift, but there’s one very important distinction: Enumerations and structures are value types. Instances of enumerations and structures are copied when they are passed to a function or assigned to a variable or constant. This means that you can have multiple copies of a structure or enumeration instance, each with its own values that are independent of the others.
Whether symbols or text, operators in Swift act on operands, which are values — either specific values (such as 17.5) or expressions that yield values (such as 16.5 + 1). Combining an operator with the appropriate number of operands yields a value which can then be used itself as an operand in another operation.
The Master-Detail Application template uses a split-view controller in some cases and a navigation controller in others. Originally (that is, with the launch of iPad), the split-view controller was intended for iPad, and the navigation controller was intended for iPhone. In 2014, with the advent of iPhone 6 Plus, the implementation changed.
Xcode “watches” your keystrokes, which enables it to suggest code as you type. This feature is called code completion, and it’s a great time‐saver. Here are some examples of its use, along with some things to watch out for — just as you can sometimes make mistakes, so can Xcode’s code completion! Code completion is the name of the technology.
Although building the interface is not strictly speaking a Swift process because Interface Builder builds the code for you, it’s worthwhile taking a look at how you write code for outlets and actions using Xcode and Interface Builder (which is built into it). In order to let people interact with social media from Locatapp, they need an action button which is typically placed at the right end of a navigation bar, as you will see in the following steps.
A protocol is introduced in Swift by the keyword protocol. It contains the ­declarations that must be implemented by the types that adopt the protocol. The most common elements of a protocol are methods and properties. The example shown here uses a single property, but multiple properties in a ­protocol are permitted.
Here, you explore the inner workings of Swift classes, structures, and enumerations (at least the inner workings that are common to all of them — refer to the table). Features in Classes, Structures, and Enumerations Feature Classes Structures Enumerations Instances X X X Properties X X computed properties only Methods X X X Subscripts X X X Initializers X X X Extensions X X X Protocols X X X Inheritance X Type casting X Deinitializers X ARC X In Locatapp (actually the Master-Detail Application template) you can see two views at the same time when you run the app on an iPhone 6 Plus or any of the iPad models.
One of the most commonly asked questions new Swift developers ask is, Can I use an old Mac to develop with Swift (or Objective‐C or Cocoa or Cocoa Touch)? The answer depends on how old your Mac is. In most cases, Macs dating back as much as five years tend to be usable with current development tools. What does need to be updated when you start developing — at least in many cases — is your operating system.
Consider the concept of encapsulation, an important concept of object‐oriented programming. The idea behind encapsulation is that objects should be opaque: You should not be able to tell what’s inside an app’s data, what functionality it contains, or what operations it carries out. Doing this makes your objects flexible and reusable.
In the world of Swift, you may want to rethink how you use enumerations. Whereas in C, structures and enumerations are often used as simple types (that is, more or less as a way of saving keystrokes or organizing the code), structures, enumerations, and classes in Swift are all object‐oriented first‐class types.
The Master‐Detail Application template in Swift, and thus the Locatapp, uses a UITableViewController to display the master list of events. Table views are very common in Cocoa Touch and, on the Mac, in Cocoa. A great deal of the work is done for you already, and two protocols play a key role in the structure. Table views on both OS X and iOS integrate very well with Core Data; the combination is frequently used as it is in Locatapp.
As you browse through your Swift code in Xcode or in a playground, you can hone in on areas you’re concerned with by folding and unfolding the sections of code you’re not interested in at the moment. Folding and unfolding affects the display only: The code is still there. Folded code will be compiled. Folding and unfolding is available for syntactic elements of code.
You may not have explored any Swift syntax yet, but you can still experiment with it. Here, you learn how to test the results of a line of code in a playground, and then how to check the syntax of your code within a playground. Testing a line of code The results of any code you type into the playground can be seen more or less instantly.
You need to choose a name for your project and its targets. Actually, your project can have multiple targets, each with its own name. Name your project with a simple one‐word short name (eight letters or fewer) that doesn’t contain non‐letter or non‐number characters such as spaces, dollar signs, or tildes. For later reference, here are a few of the options that you can consider as you are more comfortable with Xcode and app development.
Playgrounds are part of Xcode. You can use and reuse a single playground as a scratchpad or you can create a variety of unique playgrounds to test various features of your app. The choice is yours. Keep your playgrounds in a Playgrounds folder on your desktop. At the root level of this folder keep a few playgrounds lying around.
iOS Simulator is built into Xcode. It lets you run your Swift app as if it were running on a device such as iPhone or iPad. It’s a key tool in app development. iOS Simulator can’t do certain things that an actual device can do. For example, it can manage iCloud synchronization, but in iOS Simulator this is done with a menu command (Debug→Trigger iCloud Sync).
New releases of Xcode (downloadable from developer.apple.com for the beta and pre-release versions and from the Mac App Store for released versions) include documentation and APIs for new versions of Swift and the Cocoa and Cocoa Touch APIs. If you need to load older versions, go to the Downloads tab at Xcode→Preferences to review what needs to be downloaded.
Fix‐It is related to code completion in Swift in that it relies on the background ­processing of the text that you type, but it goes beyond just correcting typos. (Fix‐It is the user interface name for code completion.) The following figure uses the Master‐Detail Application template to demonstrate this. Code completion can help you complete code when you type var myVar: S.
The figure shows an example of using a playground in Swift. In this case, you're testing a for loop. Note that the number of times the loop has iterated appears at the right instead of the values. You can track value inside a loop. In the next figure, the loop is changed so that a local variable is set to the value of the counter.
When you add Swift’s features, enumerations become much more class‐like. They are no longer just collections of constants because they can now have their own properties and functions. Here’s what a Swift enumeration can look like: enum ParkPlace: Int { case park, pool, bars, track } With a bit of respacing, however, this can look very much like a classic C enum: enum ParkPlace: Int { case park case pool case bars case track } You can assign an enumeration value to a variable in Swift using code like this: let myPlace = ParkPlace.
Swift is Apple’s programming language for developers to use with iOS and OS X devices.Swift has been designed both to work alongside its predecessor, Objective-C, and to one day be Objective-C’s replacement. When you develop apps for iOS or OS X, you use the Xcode development tool (technically an Integrated Development Environment, or IDE), the Cocoa or Cocoa Touch frameworks, and a programming language —either Objective-C or Swift.
As with other languages, Swift provides developers a common library of utility code that’s frequently used in development. A library like this is separate from the language itself, although it uses the language’s syntax and features. Although you can replace this library with another, non-standard one, most people prefer the standard library, and, in fact, replacements are very rare.

App Development

Swift’s handling of types is similar to other languages, but each language has different emphases and rules. In general, these rules have to do with the ways typing must be implemented in cases where there is ambiguity. How much does the language (or its compiler or runtime library) do to ensure type compatibility?
After you have created a new Swift project from a template and are chomping at the bit and ready to get going — run the app. When it runs, you should see a map when iOS Simulator is in landscape mode (use Hardware→Rotate Right/Left to get to the landscape view). If the app doesn’t run from the basic template, it won’t run for your further additions.
Classes are the heart of any object-oriented programming language. Unlike classes in Objective-C and some other languages, Swift’s classes need no header declaration. Instead, you get the entire class (or structure or enumeration) definition in a format like this: class MyClass { var storedNumber: Int = 0 init (myNumber storedNumber: Int) { self.
Swift implements type safety, which basically means that you can’t use a variable inappropriately for the terms of its type. In other words, according to the rules of type safety, you can divide by zero — that’s not a type error — but you can’t perform an arithmetic operation with a string unless you do some conversions first.
In Swift, backing variables are explicitly declared if needed (usually in code converted from Objective‐C). Also, getters need not use the get keyword. Swift properties can be variables or constants; each type can be either stored or computed, as follows: Declaring a variable property: A variable is introduced with the keyword var as in: var _fetchedResultsController: NSFetchedResultsController?
Code completion and Fix‐It can both help you speed up your typing and writing of Swift code. Code snippets in the library go even further: They are snippets of code you can just drag into your own code. You can use a snippet as‐is, but many have tokens — highlighted areas that you can customize with your own variable names or other customizations.
Inside an enumeration within Swift, you can declare variables or constants. As you can see in the figure and the following listing, the enumeration contains a static variable consisting of an array with the five cases of the enumeration. enum Place: String { case park = "park", pool = "swimming pool", bars = "climbing bars", track1 = "running track", track2 = "walking track" static let facilities = [park, pool, bars, track1, track2] } Work through the following steps to explore the code you see here: Declare the Place enumeration.
You can create a workspace in Swift that contains several projects. The workspace, project folders, and the files within them are managed by Xcode, subject to settings you create in the File inspector in the utilities area. Within a project folder, you create files and groups of files using Xcode. The groups of files you see in the project navigator may or may not be folders on disk.
With the same basic code, you can add a function to an enumeration in Swift. This is something you haven’t seen in C and perhaps not in other languages either. It’s a new way of looking at enumerations. Adding a simple function to an enumeration Here is the function that’s added to the enumeration. You can place it anywhere (except, of course, not in the middle of the case): func enumFunction () -> Int { return -17 } The function is named enumFunction and it returns an Int with the value of –17.
As of the start of 2015, almost all of the Cocoa and Cocoa Touch frameworks are written in Objective-C, and Swift can use them easily. (Of course it can; this was one of Swift’s design goals.) Even so, some aspects of the frameworks work well in Swift, but perhaps not as elegantly as you might like. In particular, these include the issues involved with passing pointers (used a great deal in the Objective-C frameworks) to and from Swift.
In the case of a simple Xcode project (such as Locatapp), the structure is very simple: one workspace with one project with one target. If you want to, you can move onto a workspace with multiple projects, each of which has multiple targets. Alternatively, you can opt for a workspace with a single project with multiple targets.
https://cdn.prod.website-files.com/6630d85d73068bc09c7c436c/69195ee32d5c606051d9f433_4.%20All%20For%20You.mp3

Frequently Asked Questions

No items found.