1. Welcome to Modern Swift

When Apple introduced the Swift programming language in 2014, it offered a performance-tuned type-safe modern programming language intended to supplant Objective-C. The new language included protocol-oriented development, type inferencing, automatic reference counting, generics, first-class function objects, overloading, nullability, optionals, and more. Swift overhauled control mechanisms and constructs, enhancing features like switches and enumerations to add flexibility and power to Cocoa and Cocoa Touch projects.

Lead developer Chris Lattner began Swift language development in 2010. The project grew, and by 2013 had become a major focus for Apple’s developer tools group. After the 2014 launch, Chris Lattner described the design effort that fed the Swift project on his blog: “The Swift language is the product of tireless effort from a team of language experts, documentation gurus, compiler optimization ninjas, and an incredibly important internal dogfooding group who provided feedback to help refine and battle-test ideas. Of course, it also greatly benefited from the experiences hard-won by many other languages in the field, drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.”

The language did not express its true potential until WWDC 2015. At that time, Swift evolved to version 2, with a completely redesigned error-handling system, better integration with legacy APIs, and feature upgrades that connected the language closer to its functional roots. That’s not to say Swift has arrived yet. Swift 2 happened, but Swift is nowhere near done. A recurring theme during WWDC presentations was expressed in phrases such as “in a future update,” “in a future release,” and “when we get time to implement that.” Huge changes happened at WWDC, not the least of which affected foundational concepts that underpin nearly every line of code you write.

Since Apple introduced the language, Swift has remained in constant flux. From beta to beta, dot release to dot release, new features and updated syntax mean source code that compiles in one release might not in the next. I expect that Swift will change every six months or so for the next few years, at a minimum, before the rate of updates begins to slow down and a stable language emerges.

Swift is now at an awkward state. It still shows rough edges, but it has too much momentum and it’s too important to the Apple developer community to ignore. It’s time to jump aboard if you haven’t already. Just acknowledge the realities. It’s been a long, tough, frustrating environment to work in.

I feel comfortable enough committing myself to an actual book project about Swift because of two things. First, Swift’s most fundamental features have mostly coalesced. Structures, enumerations, and classes are unlikely to be hit hard by profound architectural redesign, although many small features continue to evolve. Second, Apple has committed to offering migration tools that enable you to upgrade your source to the latest language release. When Swift changed its basic printing function from println() to print(), Xcode’s migrator was there to facilitate the change.

Developers are no longer working in such early betas that the language doesn’t know what it is. Swift has reached the point where Apple is primarily updating techniques and procedures, not core language concepts—well, not a lot of core language concepts. Coding in early betas was ridiculous. Today’s Swift is merely frustrating. It can also be greatly rewarding. The language isn’t finished, but it is now usable, learnable, and a worthy target for your time and attention.

Apple has committed to making Swift the future. Now is the perfect time to jump on the Swift train and see where it takes you. Don’t look at Swift 2 and say, “I’m too late to board this train” or “How is it possible that version 2 of a language is still beta?” I invite you to use basic Swift math to convert the latest release into its true version number:

Official Swift version N = Unofficial Swift(version: N * 0.1)

This is a silly but amusing way of saying “Version 2 still feels behind where a version 1 release should be.” The numeric constant may rise over time from 0.1 if Swift continues its rapid evolution.

Migrating Code

It might seem a little odd to kick off a language book by discussing code migration, but this entire chapter is devoted to the notion that Swift is lovable, worthy, and slightly unready for prime time. Knowing how to develop in a continuously moving landscape is a valuable skill.

Xcode’s Swift migration support was first introduced with Swift 1.2. A critical feature for a changing language, the assistant locates outdated syntax and offers a smooth path to modernization. The exact details for this tool may change over time, but Apple has committed to providing a migration tool to support developers from release to release.

How to Migrate

You find Convert under the Edit menu. Figure 1-1 shows this menu in a beta Xcode 7 release. Once you select Convert, Xcode steps you through the process of migrating your code for an entire target.

Image

Figure 1-1 Xcode enables you to convert Swift source code to modern syntax.

Select the targets you wish to upgrade, as in Figure 1-2. You may be prompted to enable repository snapshots. Whether you use a git commit (you can substitute your preferred version control system) or the offered Xcode snapshot, a commit of some kind allows you to revert your project to its pre-upgrade state and is highly recommended.

Image

Figure 1-2 Select which targets in your project you wish to convert.

Xcode scans the files that make up your project and highlights language changes (see Figure 1-3). You approve or reject the updates by clicking Save or Cancel.

Image

Figure 1-3 Xcode offers side-by-side comparisons showing the modern (After Conversion) and older (Before Conversion) syntax. The updates are to the left and the original code to the right.

Each upgrade point is marked with a red dot, as you see in Figure 1-3. The dot is paired with a small numbered gray oval. Click each dot to view a detailed explanation of the update change. Click the gray oval to discard a recommended update.

A table of contents appears at the top-left side of the Review Changes pane. It enables you to select individual files to review. Xcode presents the After Conversion and Before Conversion versions in the left and right panes. If you are at all unsure about which pane is which, check the titles at the very bottom of each pane. Xcode explicitly documents the conversion role as well as the filename. When you’re finished with your review, click Save. Xcode applies its updates, and you’re ready to use the code with the latest compiler.

Migration Lessons

Following the version 2 beta launch, developers started upgrading Apple-supplied playgrounds such as the March 2015 Mandelbrot sample (https://developer.apple.com/swift/blog/?id=26). Some had wasted hours trying to get the samples to work. Where possible, don’t upgrade your code by hand; the migrator does a better job. It performs upgrades mechanically and has no preconceptions about the material it’s working on. By re-downloading the original and automating the upgrade, those developers had code running in just a few minutes.

The upgrade process isn’t a panacea. The migrator won’t find logic errors or flawed coding, and it cannot account for paradigm shifts. For example, to use a rather involved Swift concept, consider the way a Swift application deals with failure conditions. The Swift migrator can’t move apps away from Swift 1.2–style if-let pyramids to Swift 2 guard statements. You need to incorporate those types of transitions by hand. The paradigm has shifted, but Xcode can only adjust syntax. It cannot take into account best practices or pattern updates.

Xcode also can’t upgrade code that’s too far out of date. The initial 1.1 to 1.2 migrator couldn’t handle 1.0 beta Swift. Keeping your code base updated and current and ready for each successive language leap forward is your job. This requires a big investment of time, but it’s necessary if you’re going to commit to the Swift language at this time.

Migration means review. This is the point of the side-by-side comparisons you saw in Figure 1-3. It’s why you’ll want to conduct general code inspections after upgrades. My experiences have been positive. That doesn’t diminish the fact that language migrations involve cost both in time and loss of control.

The most important thing you can learn from Swift migration is the value of a good suite of test cases. Investing time into code validation is a critical part of keeping your libraries and applications current, modern, and running. A sufficient suite provides full code coverage and ensures that your functionality passes a minimal validation set. If your tests are written in Swift, allocate time and overhead to migrating the tests as well. Then automate your testing post-upgrade just as Xcode automates the migration itself.

Using Swift

Swift is a general-purpose language that can be compiled or run as a script, used at the command line, or used in standalone apps. From compiled apps to scripts, here’s a quick survey of some ways Swift builds executable code.

Compiled Applications

Most typically, you use Swift to build applications and extensions for iOS, OS X, tvOS, and watchOS targets (see Figure 1-4). Swift is a modern, type-safe language that offers fast, efficient code generation. A complete development solution, Swift integrates with Apple’s full range of developer APIs. Create apps using either pure Swift code or in hybrid language projects that bridge Swift with C and Objective-C.

Image

Figure 1-4 Swift is the new language of choice for Apple application development.

Frameworks and Libraries

Swift isn’t just for building applications with traditional user interfaces. The Swift language enables you to create frameworks, bundles, services, and command-line utilities. (Swift does not yet support the creation of static libraries.) Xcode offers a wide range of built-in templates that support the Swift language so you can get off to a running start on your next big project (see Figure 1-5).

Image

Figure 1-5 Swift builds targets like command-line utilities and frameworks.

Scripting

Swift is also a scripting language. Use it to build quick shell utilities. The following example scrapes iTunes to look up prices of items specified with an App Store ID. Other than the shebang on the first line (the hash sign followed by the exclamation point), this script is indistinguishable from a source you’d compile for a command-line utility:

#!/usr/bin/xcrun swift
import Cocoa
var arguments = Process.arguments
for appID in arguments.dropFirst() {
    let urlString = "https://itunes.apple.com/lookup?id=(appID)"
    guard let url = NSURL(string: urlString) else {continue}
    guard let data = NSData(contentsOfURL: url) else {continue}
    if let json =
        try NSJSONSerialization.JSONObjectWithData(data, options: [])
            as? NSDictionary,
        resultsList = json["results"] as? NSArray,
        results = resultsList.firstObject as? NSDictionary,
        name = results["trackName"] as? String,
        price = results["price"] as? NSNumber {
            let words = name.characters.split(
                isSeparator:{$0 == ":" || $0 == "-"}).map(String.init)
            let n = words.first!
            print ("(n): (price)")
    }
}

REPL

REPL stands for “read eval print loop,” an interactive top-level shell that reads user expressions, evaluates them, and prints results. The Swift REPL provides an environment for instant testing and exploration. Just run swift at the command line, and you enter an interactive setting.

The Swift REPL maintains ongoing state that enables you to create functions, which you can later refer to, and define structures and classes. Just type expressions for instant evaluation:

% swift
Welcome to Apple Swift version 2.0 (700.0.42.1 700.0.53).
Type :help for assistance.
  1> print("hello world")
hello world
  2> func greet() {
  3.     print("hello world")
  4. }
  5> greet()
hello world
  6> 1 + 2 + 3 + 4
$R0: Int = 10

Playgrounds

Playgrounds are Swift REPLs on steroids. They offer the same kind of immediate interpreted gratification you expect from a REPL but supplement that feedback with sophisticated visualization and documentation tools (see Figure 1-6). Playgrounds enable you to explore the Swift language, test routines, prototype quick solutions, delve into Cocoa/Cocoa Touch APIs, and create flexible interactive documents.

Image

Figure 1-6 This Apple-sourced playground showcases Mandelbrot sets, complex numbers with beautiful fractal boundary features.

Other Swift

At WWDC 2015, Apple announced that Swift would be released as an open source language with Apple-sourced compilers for iOS, OS X, and eventually Linux platforms. Those who wish to explore Swift from other platforms can use online interpreters. Swiftstub (http://swiftstub.com) enables Swift programming from any web browser (see Figure 1-7).

Image

Figure 1-7 Interact with Swift from any web browser.

Learning Swift

This cookbook is neither a “getting started” tutorial nor an exhaustive reference. Download a copy of The Swift Programming Language—a free ebook offered by Apple on the iBooks store—and work through the guided tour section. This ebook is regularly updated as the language evolves; an extensive Revision History section lets you explore documentation and language changes by date.

A second Apple ebook, Using Swift with Cocoa and Objective-C, is just as essential. It provides an overview of the topics related to interoperability between the two languages and the details of API calls. It’s a much shorter volume than The Swift Programming Language due to its tight focus.

Both books are available on Apple’s website as well as in iBooks. I prefer web-based search engines to the limited iBooks in-book tools. Web searches can use Boolean clauses and aren’t limited to exact phrase matching. In contrast, iBooks searches are limited to words and page numbers. Matches against common words (think for or switch) are particularly frustrating to deal with in iBooks, which doesn’t offer the context-limiting support you find with popular search engines.

Apple’s online Swift Standard Library Reference (search the web for it as its URL regularly changes) provides an indispensable overview of Swift’s base functionality layer. It offers an overview of fundamental data types, common data structures, functions, methods, and protocols. If you stop learning Swift at the language basics, you’re missing out on this critical portion of core language expressiveness. SwiftDoc (http://swiftdoc.org) offers auto-generated documentation for Swift’s standard library. This is the same documentation you find when you Command-click symbols in Xcode but presented in easier-to-read webpages. It’s a terrific resource.

The Apple Swift blog (https://developer.apple.com/swift/blog/) is updated about once a month, but its coverage includes can’t-miss topics related to language features and case studies. Its mission statement speaks about behind-the-scenes peeks into language design, but its focus over time has been more practical how-to articles. The blog’s resources page (https://developer.apple.com/swift/resources/) further provides links to a set of essential Swift and Xcode materials, including iTunes U courses, videos, sample code, and a link to the official Swift Standard Library Reference.

The redesigned Apple Developer Forums (https://forums.developer.apple.com/community/xcode/swift) provide access to Swift engineers, lively discussions, and up-to-date how-to information. You will also find important language information archived at the old forums site (https://devforums.apple.com/index.jspa); navigate to Developer Tools > Language > Swift.

Also amazing is ASCII WWDC (http://asciiwwdc.com). Enter keywords and search through years of WWDC talks. This website helps you track down presentations specific to the Swift language and the Xcode tools that support Swift development.

If you use Internet Relay Chat (IRC) peer support, the Freenode (chat.freenode.net) #swift-lang room offers access to pro-level coding advice. It’s a language-specific room, so if you need help with OS-specific APIs, visit #iphonedev or #macdev instead. A final room, #cocoa-init, is set up specifically to help mentor developers new to iOS and OS X.

Wrap-up

With Swift, Apple committed itself to redefining its developer tool suite. Swift 2 represents the start of that journey, not the end. Its tools, modules, and the language itself will and must continue to grow in the foreseeable future. Swift is nowhere near a stopping point at this time.

As best practices coalesce and design patterns emerge, now is a great time to begin transitioning code and techniques to the new bright future. The chapters that follow in this cookbook survey key areas of Swift development. They’ll enable you to cherry-pick those areas you need to learn and offer hard-won techniques for you to incorporate into your code.

Good luck on your journey.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.162.105