Book Image

Mastering macOS Programming.

By : Stuart Grimshaw, Gregory Casamento
Book Image

Mastering macOS Programming.

By: Stuart Grimshaw, Gregory Casamento

Overview of this book

macOS continues to lead the way in desktop operating systems, with its tight integration across the Apple ecosystem of platforms and devices. With this book, you will get an in-depth knowledge of working on macOS, enabling you to unleash the full potential of the latest version using Swift 3 to build applications. This book will help you broaden your horizons by taking your programming skills to next level. The initial chapters will show you all about the environment that surrounds a developer at the start of a project. It introduces you to the new features that Swift 3 and Xcode 8 offers and also covers the common design patterns that you need to know for planning anything more than trivial projects. You will then learn the advanced Swift programming concepts, including memory management, generics, protocol orientated and functional programming and with this knowledge you will be able to tackle the next several chapters that deal with Apple’s own Cocoa frameworks. It also covers AppKit, Foundation, and Core Data in detail which is a part of the Cocoa umbrella framework. The rest of the book will cover the challenges posed by asynchronous programming, error handling, debugging, and many other areas that are an indispensable part of producing software in a professional environment. By the end of this book, you will be well acquainted with Swift, Cocoa, and AppKit, as well as a plethora of other essential tools, and you will be ready to tackle much more complex and advanced software projects.
Table of Contents (28 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Dedication
Preface
18
LLDB and the Command Line

Optionals


In Chapter 2, Basic Swift, we looked at the raw basics of Swift's optionals. In this section, we'll flesh that out to cover their most essential use cases.

Conditional downcasting

We have already seen how to safely unwrap an optional value:

if let id = Int("12364677") 
{ 
  print("Valid id: \(id)") 
} 

In this case, we know that the Intinit method that takes a String argument returns an optional Int. We only need to test whether it contains a value or nil, and if it contains a value, we know that we can unwrap the value to get an Int.

If, however, we don't know what type may be returned by a function, we can attempt a downcast with the as? keyword:

let jsonResponse: [String: Any] = ["user": "Elliot", 
                                   "id": "Elliot2016"] 

if let userString = jsonResponse["user"] as? String 
{ 
  print("User string contains \(userString.characters.count) 
  characters") 
} 

This code will print the required information, since the downcast succeeds.

Now try this code:

if...