100% found this document useful (7 votes)
75 views

iOS 11 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 4th Edition Matt Neuburg instant download

The document is a promotional text for various editions of programming books by Matt Neuburg, specifically focusing on iOS development using Swift, Xcode, and Cocoa. It includes links to download the books and highlights the evolution of the editions from iOS 10 to iOS 14. Additionally, it provides a detailed table of contents for the iOS 11 Programming Fundamentals book, covering various programming concepts and Xcode project management.

Uploaded by

zucal4alemurf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (7 votes)
75 views

iOS 11 Programming Fundamentals with Swift Swift Xcode and Cocoa Basics 4th Edition Matt Neuburg instant download

The document is a promotional text for various editions of programming books by Matt Neuburg, specifically focusing on iOS development using Swift, Xcode, and Cocoa. It includes links to download the books and highlights the evolution of the editions from iOS 10 to iOS 14. Additionally, it provides a detailed table of contents for the iOS 11 Programming Fundamentals book, covering various programming concepts and Xcode project management.

Uploaded by

zucal4alemurf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

iOS 11 Programming Fundamentals with Swift Swift

Xcode and Cocoa Basics 4th Edition Matt Neuburg


download

https://textbookfull.com/product/ios-11-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-4th-edition-matt-neuburg/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

iOS 10 Programming Fundamentals with Swift Swift Xcode


and Cocoa Basics 3rd Edition Matt Neuburg

https://textbookfull.com/product/ios-10-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-3rd-edition-matt-neuburg/

iOS 12 Programming Fundamentals with Swift Swift Xcode


and Cocoa Basics 5th Edition Matt Neuburg

https://textbookfull.com/product/ios-12-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-5th-edition-matt-neuburg/

iOS 13 Programming Fundamentals with Swift Swift Xcode


and Cocoa Basics 1st Edition Matt Neuburg

https://textbookfull.com/product/ios-13-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-1st-edition-matt-neuburg/

iOS 12 Programming Fundamentals with Swift Swift Xcode


and Cocoa Basics 5th Edition Matt Neuburg

https://textbookfull.com/product/ios-12-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-5th-edition-matt-
neuburg-2/
iOS 12 Programming Fundamentals with Swift Swift Xcode
and Cocoa Basics 5th Edition Matt Neuburg

https://textbookfull.com/product/ios-12-programming-fundamentals-
with-swift-swift-xcode-and-cocoa-basics-5th-edition-matt-
neuburg-3/

iOS 14 Programming Fundamentals with Swift Covers iOS


14 Xcode 12 and Swift 5 3 7th Edition Matt Neuburg

https://textbookfull.com/product/ios-14-programming-fundamentals-
with-swift-covers-ios-14-xcode-12-and-swift-5-3-7th-edition-matt-
neuburg/

Learn iOS 11 Programming with Swift 4 Craig Clayton

https://textbookfull.com/product/learn-ios-11-programming-with-
swift-4-craig-clayton/

Programming iOS 14 11th Edition Matt Neuburg

https://textbookfull.com/product/programming-ios-14-11th-edition-
matt-neuburg/

iOS 11 Swift Programming Cookbook Solutions and


Examples for iOS Apps 1st Edition Vandad Nahavandipoor

https://textbookfull.com/product/ios-11-swift-programming-
cookbook-solutions-and-examples-for-ios-apps-1st-edition-vandad-
nahavandipoor/
Xc
C o e 9,
od
ve a n
rs d
i O Sw
S 1 if
1, t 4
iOS 11
Programming
Fundamentals
with Swift
SWIFT, XCODE, AND COCOA BASICS

Matt Neuburg
FOURTH EDITION

iOS 11 Programming
Fundamentals with Swift
Swift, Xcode, and Cocoa Basics

Matt Neuburg

Boston
iOS 11 Programming Fundamentals with Swift, Fourth Edition
by Matt Neuburg
Copyright © 2018 Matt Neuburg. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://oreilly.com/safari). For more information, contact our corporate/insti‐
tutional sales department: 800-998-9938 or corporate@oreilly.com.

Editor: Rachel Roumeliotis Cover Designer: Karen Montgomery


Production Editor: Kristen Brown Interior Designer: David Futato
Proofreader: O’Reilly Production Services Illustrator: Matt Neuburg
Indexer: Matt Neuburg

April 2015: First Edition


October 2015: Second Edition
October 2016: Third Edition
October 2017: Fourth Edition

Revision History for the Fourth Edition


2017-09-26: First release

See http://oreilly.com/catalog/errata.csp?isbn=0636920107415 for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. iOS 11 Programming Fundamentals
with Swift, the image of a harp seal, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.

ISBN: 978-1-491-99931-8
[LSI]
Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Part I. Language
1. The Architecture of Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Ground of Being 3
Everything Is an Object? 5
Three Flavors of Object Type 6
Variables 6
Functions 8
The Structure of a Swift File 9
Scope and Lifetime 11
Object Members 13
Namespaces 13
Modules 14
Instances 15
Why Instances? 17
The Keyword self 19
Privacy 20
Design 22
Object Types and APIs 23
Instance Creation, Scope, and Lifetime 25
Summary and Conclusion 26

2. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Function Parameters and Return Value 27
Void Return Type and Parameters 31
Function Signature 32

iii
External Parameter Names 32
Overloading 34
Default Parameter Values 35
Variadic Parameters 35
Ignored Parameters 36
Modifiable Parameters 37
Function In Function 40
Recursion 42
Function As Value 42
Anonymous Functions 45
Define-and-Call 51
Closures 52
How Closures Improve Code 54
Function Returning Function 55
Closure Setting a Captured Variable 58
Closure Preserving Its Captured Environment 59
Escaping Closures 60
Curried Functions 61
Function References and Selectors 62
Function Reference Scope 64
Selectors 65

3. Variables and Simple Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69


Variable Scope and Lifetime 69
Variable Declaration 71
Computed Initializer 75
Computed Variables 75
Setter Observers 79
Lazy Initialization 80
Built-In Simple Types 82
Bool 82
Numbers 84
String 91
Character and String Index 96
Range 101
Tuple 103
Optional 106

4. Object Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119


Object Type Declarations and Features 119
Initializers 121
Properties 127

iv | Table of Contents
Methods 130
Subscripts 132
Nested Object Types 135
Instance References 135
Enums 137
Raw Values 138
Associated Values 140
Enum Initializers 142
Enum Properties 143
Enum Methods 144
Why Enums? 145
Structs 146
Struct Initializers, Properties, and Methods 146
Struct As Namespace 148
Classes 148
Value Types and Reference Types 149
Subclass and Superclass 155
Class Initializers 160
Class Deinitializer 168
Class Properties and Methods 168
Polymorphism 170
Casting 174
Casting Down 175
Type Testing and Casting Down Safely 175
Type Testing and Casting Optionals 176
Bridging to Objective-C 177
Type Reference 178
Protocols 183
Why Protocols? 185
Protocol Type Testing and Casting 187
Declaring a Protocol 188
Protocol Composition 189
Optional Protocol Members 190
Class Protocol 192
Implicitly Required Initializers 192
Literal Convertibles 194
Generics 195
Generic Declarations 198
Type Constraints 200
Explicit Specialization 202
Associated Type Chains 204
Where Clauses 207

Table of Contents | v
Extensions 211
Extending Object Types 211
Extending Protocols 213
Extending Generics 215
Umbrella Types 217
Any 217
AnyObject 219
AnyClass 221
Collection Types 222
Array 222
Dictionary 238
Set 245

5. Flow Control and More. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251


Flow Control 251
Branching 252
Loops 264
Jumping 268
Key Paths 284
Operators 286
Privacy 290
Private and Fileprivate 291
Public and Open 292
Privacy Rules 293
Introspection 293
Memory Management 294
Memory Management of Reference Types 295
Exclusive Access to Value Types 302

Part II. IDE


6. Anatomy of an Xcode Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
New Project 307
The Project Window 309
The Navigator Pane 311
The Utilities Pane 316
The Editor 318
The Project File and Its Dependents 320
The Target 322
Build Phases 323
Build Settings 325

vi | Table of Contents
Configurations 326
Schemes and Destinations 327
From Project to Running App 330
Build Settings 333
Property List Settings 333
Nib Files 334
Additional Resources 335
Code Files 338
Frameworks and SDKs 338
The App Launch Process 340
The Entry Point 341
UIApplicationMain 342
App Without a Storyboard 344
Renaming Parts of a Project 345

7. Nib Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347


The Nib Editor Interface 348
Document Outline 350
Canvas 352
Inspectors and Libraries 355
Nib Loading 356
When Nibs Are Loaded 356
Manual Nib Loading 358
Connections 360
Outlets 360
The Nib Owner 361
Automatically Configured Nibs 365
Misconfigured Outlets 366
Deleting an Outlet 368
More Ways to Create Outlets 368
Outlet Collections 372
Action Connections 372
More Ways to Create Actions 374
Misconfigured Actions 376
Connections Between Nibs — Not! 376
Additional Configuration of Nib-Based Instances 377

8. Documentation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
The Documentation Window 381
Class Documentation Pages 383
Quick Help 386
Symbol Declarations 388

Table of Contents | vii


Header Files 389
Sample Code 390
Internet Resources 390

9. Life Cycle of a Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393


Runtime Environment 393
Backward Compatibility 394
Device Type 396
Version Control 397
Editing and Navigating Your Code 400
Autocompletion 401
Snippets 403
Structure Stubs 404
Fix-it and Live Syntax Checking 404
Navigation 405
Finding 407
Refactoring 408
Running in the Simulator 409
Debugging 410
Caveman Debugging 410
The Xcode Debugger 412
Testing 419
Clean 424
Running on a Device 425
Obtaining a Developer Program Membership 426
Signing an App 427
Automatic Signing 428
Obtaining a Development Certificate Manually 430
Obtaining a Development Provisioning Profile Manually 431
Running the App 434
Managing Development Certificates and Devices 434
Profiling 435
Gauges 435
Memory Debugging 436
Instruments 437
Localization 440
Distribution 445
Making an Archive 445
Obtaining a Distribution Certificate 446
Obtaining a Distribution Profile 447
Ad Hoc Distribution 448
Final App Preparations 450

viii | Table of Contents


Screenshots and video previews 453
Property list settings 454
Submission to the App Store 455

Part III. Cocoa


10. Cocoa Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Subclassing 461
Categories and Extensions 464
How Swift Uses Extensions 464
How You Use Extensions 465
How Cocoa Uses Categories 466
Protocols 467
Informal Protocols 469
Optional Methods 470
Some Foundation Classes 472
NSRange and NSNotFound 473
NSString and Friends 475
NSDate and Friends 478
NSNumber 480
NSValue 481
NSData 482
NSMeasurement and Friends 483
Equality and Comparison 484
NSArray and NSMutableArray 485
NSDictionary and NSMutableDictionary 487
NSSet and Friends 488
NSIndexSet 489
NSNull 489
Immutable and Mutable 490
Property Lists 491
Codable 492
Accessors, Properties, and Key–Value Coding 495
Swift Accessors 497
Key–Value Coding 498
Uses of Key–Value Coding 500
KVC and Outlets 501
Key Paths 502
Array Accessors 503
The Secret Life of NSObject 504

Table of Contents | ix
11. Cocoa Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
Reasons for Events 508
Subclassing 508
Notifications 510
Receiving a Notification 511
Unregistering 513
Posting a Notification 514
Timer 515
Delegation 517
Cocoa Delegation 517
Implementing Delegation 519
Data Sources 521
Actions 522
The Responder Chain 525
Deferring Responsibility 526
Nil-Targeted Actions 526
Key–Value Observing 527
Swamped by Events 531
Delayed Performance 534

12. Memory Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537


Principles of Cocoa Memory Management 537
Rules of Cocoa Memory Management 538
What ARC Is and What It Does 539
How Cocoa Objects Manage Memory 540
Autorelease Pool 541
Memory Management of Instance Properties 543
Retain Cycles and Weak References 544
Unusual Memory Management Situations 546
Notification Observers 546
KVO Observers 548
Timers 548
Other Unusual Situations 550
Nib Loading and Memory Management 550
Memory Management of CFTypeRefs 551
Property Memory Management Policies 553
Debugging Memory Management Mistakes 555

13. Communication Between Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557


Visibility by Instantiation 558
Visibility by Relationship 560
Global Visibility 561

x | Table of Contents
Notifications and Key–Value Observing 563
Model–View–Controller 563

A. C, Objective-C, and Swift. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601

Table of Contents | xi
Preface

On June 2, 2014, Apple’s WWDC keynote address ended with a shocking announce‐
ment: “We have a new programming language.” This came as a huge surprise to the
developer community, which was accustomed to Objective-C, warts and all, and
doubted that Apple could ever possibly relieve them from the weight of its venerable
legacy. The developer community, it appeared, had been wrong.
Having picked themselves up off the floor, developers immediately began to consider
this new language — Swift — studying it, critiquing it, and deciding whether to use it.
My own first move was to translate all my existing iOS apps into Swift; this was
enough to convince me that, for all its faults, Swift deserved to be adopted by new
students of iOS programming, and that my books, therefore, should henceforth
assume that readers are using Swift.
Three years later, that decision has proven prophetic. Programmers of iOS have
flocked to Swift in increasing numbers, and Swift itself has only improved. My iOS
apps (such as Diabelli’s Theme, LinkSame, Zotz!, TidBITS News, and my Latin and
Greek flashcard apps) have all been rewritten in Swift, and are far easier for me to
understand and maintain than their Objective-C originals.
Xcode 9 comes with Swift 4. The language has evolved greatly in its details and in the
nature of its integration with the Cocoa libraries that underlie iOS programming, but
its spirit has remained constant. The Swift language is designed from the ground up
with these salient features:
Object-orientation
Swift is a modern, object-oriented language. It is purely object-oriented: “Every‐
thing is an object.”
Clarity
Swift is easy to read and easy to write. Its syntax is clear, consistent, and explicit,
with few hidden shortcuts and minimal syntactic trickery.

xiii
Safety
Swift enforces strong typing to ensure that it knows, and that you know, what the
type of every object reference is at every moment.
Economy
Swift is a fairly small language, providing some basic types and functionalities
and no more. The rest must be provided by your code, or by libraries of code that
you use — such as Cocoa.
Memory management
Swift manages memory automatically. You will rarely have to concern yourself
with memory management.
Cocoa compatibility
The Cocoa APIs are written primarily in C and Objective-C. Swift is explicitly
designed to interface with most of the Cocoa APIs.
These features make Swift an excellent language for learning to program iOS.
The alternative, Objective-C, still exists, and you can use it if you like. Indeed, it is
easy to write an app that includes both Swift code and Objective-C code; and you may
have reason to do so. Objective-C, however, lacks the very advantages that Swift
offers. Objective-C agglomerates object-oriented features onto C. It is therefore only
partially object-oriented; it has both objects and scalar data types, and its objects have
to be slotted into one particular C data type (pointers). Its syntax can be difficult and
tricky; reading and writing nested method calls can make one’s eyes glaze over, and it
invites hacky habits such as implicit nil-testing. Its type checking can be and fre‐
quently is turned off, resulting in programmer errors where a message is sent to the
wrong type of object and the program crashes.
Recent revisions and additions to Objective-C — ARC, synthesis and autosynthesis,
improved literal array and dictionary syntax, blocks — have made it easier and more
convenient, but such patches have also made the language even larger and possibly
even more confusing. Because Objective-C must encompass C, there are limits to
how far it can be extended and revised. Swift, on the other hand, is a clean start. If
you were to dream of completely revising Objective-C to create a better Objective-C,
Swift might be what you would dream of. It puts a modern, rational front end
between you and the Cocoa Objective-C APIs.
Still, the reader will also need some awareness of Objective-C (including C). The
Foundation and Cocoa APIs, the built-in commands with which your code must
interact in order to make anything happen on an iOS device, are still written in C and
Objective-C. In order to interact with them, you have to know what those languages
would expect. For example, in order to pass a Swift array where an NSArray is
expected, you need to know what constitutes an object acceptable as an element of an
Objective-C NSArray.

xiv | Preface
Therefore, although I do not attempt to teach Objective-C in this book, I do describe
it in enough detail to allow you to read it when you encounter it in the documenta‐
tion and on the Internet, and I occasionally show some Objective-C code. Part III, on
Cocoa, is really all about learning to think the way Objective-C thinks — because the
structure and behavior of the Cocoa APIs are fundamentally based on Objective-C.
And the book ends with an appendix that details how Swift and Objective-C commu‐
nicate with one another, as well as explaining how your app can be written partly in
Swift and partly in Objective-C.

The Scope of This Book


This book is actually one of a pair with my Programming iOS 11, which picks up
exactly where this book leaves off. They complement and supplement one another.
The two-book architecture should, I believe, render the size and scope of each book
tractable for readers. Together, they provide a complete grounding in the knowledge
needed to begin writing iOS apps; thus, when you do start writing iOS apps, you’ll
have a solid and rigorous understanding of what you are doing and where you are
heading. If writing an iOS program is like building a house of bricks, this book
teaches you what a brick is and how to handle it, while Programming iOS 11 hands
you some actual bricks and tells you how to assemble them.
When you have read this book, you’ll know about Swift, Xcode, and the underpin‐
nings of the Cocoa framework, and you will be ready to proceed directly to Program‐
ming iOS 11. Conversely, Programming iOS 11 assumes a knowledge of this book; it
begins, like Homer’s Iliad, in the middle of the story, with the reader jumping with all
four feet into views and view controllers, and with a knowledge of the language and
the Xcode IDE already presupposed. If you started reading Programming iOS 11 and
wondered about such unexplained matters as Swift language basics, the
UIApplicationMain function, the nib-loading mechanism, Cocoa patterns of delega‐
tion and notification, and retain cycles, wonder no longer — I didn’t explain them
there because I do explain them here.
The three parts of this book teach the underlying basis of all iOS programming:

• Part I introduces the Swift language, from the ground up — I do not assume that
you know any other programming languages. My way of teaching Swift is differ‐
ent from other treatments, such as Apple’s; it is systematic and Euclidean, with
pedagogical building blocks piled on one another in what I regard as the most
helpful order. At the same time, I have tried to confine myself to the essentials.
Swift is not a big language, but it has some subtle and unusual corners. You don’t
need to dive deep into all of these, and my discussion will leave many of them
unexplored. You will probably never encounter them, and if you do, you will
have entered an advanced Swift world outside the scope of this discussion. To
give an obvious example, readers may be surprised to find that I never mention

Preface | xv
Swift playgrounds or the REPL. My focus here is real-life iOS programming, and
my explanation of Swift therefore concentrates on those common, practical
aspects of the language that, in my experience, actually come into play in the
course of programming iOS.
• Part II turns to Xcode, the world in which all iOS programming ultimately takes
place. It explains what an Xcode project is and how it is transformed into an app,
and how to work comfortably and nimbly with Xcode to consult the documenta‐
tion and to write, navigate, and debug code, as well as how to bring your app
through the subsequent stages of running on a device and submission to the App
Store. There is also a very important chapter on nibs and the nib editor (Interface
Builder), including outlets and actions as well as the mechanics of nib loading;
however, such specialized topics as autolayout constraints in the nib are post‐
poned to the other book.
• Part III introduces the Cocoa Touch framework. When you program for iOS, you
take advantage of a suite of frameworks provided by Apple. These frameworks,
taken together, constitute Cocoa; the brand of Cocoa that provides the API for
programming iOS is Cocoa Touch. Your code will ultimately be almost entirely
about communicating with Cocoa. The Cocoa Touch frameworks provide the
underlying functionality that any iOS app needs to have. But to use a framework,
you have to think the way the framework thinks, put your code where the frame‐
work expects it, and fulfill many obligations imposed on you by the framework.
To make things even more interesting, Cocoa uses Objective-C, while you’ll be
using Swift: you need to know how your Swift code will interface with Cocoa’s
features and behaviors. Cocoa provides important foundational classes and adds
linguistic and architectural devices such as categories, protocols, delegation, and
notifications, as well as the pervasive responsibilities of memory management.
Key–value coding and key–value observing are also discussed here.

The reader of this book will thus get a thorough grounding in the fundamental
knowledge and techniques that any good iOS programmer needs. The book itself
doesn’t show how to write any particularly interesting iOS apps, but it does constantly
use my own real apps and real programming situations to illustrate and motivate its
explanations. And then you’ll be ready for Programming iOS 11, of course!

Versions
This book is geared to Swift 4, iOS 11, and Xcode 9.
In general, only very minimal attention is given to earlier versions of iOS and Xcode.
It is not my intention to embrace in this book any detailed knowledge about earlier
versions of the software, which is, after all, readily and compendiously available in my

xvi | Preface
earlier books. The book does contain, nevertheless, a few words of advice about back‐
ward compatibility (especially in Chapter 9).
A word about method names. I generally give method names in Swift, in the style of a
function reference (as described in Chapter 2) — that is, the name plus parentheses
containing the parameter labels followed by colon. Now and then, if a method is
already under discussion and there is no ambiguity, I’ll use the bare name. In a few
places, such as Appendix A, where the Objective-C language is explicitly under dis‐
cussion, I use Objective-C method names.
Please bear in mind that Apple continues to make adjustments to the Swift language.
I have tried to keep my code up-to-date right up to the moment when the manuscript
left my hands; but if, at some future time, a new version of Xcode is released along
with a new version of Swift, some of the code in this book, and even some informa‐
tion about Swift itself, might be slightly incorrect. Please make allowances, and be
prepared to compensate.
Screenshots of Xcode were taken using Xcode 9 under macOS 10.12 Sierra. I have not
upgraded my machine to macOS 10.13 High Sierra, because at the time of this writing
it was too new to be trusted with mission-critical work. If you are braver than I am
and running High Sierra, your interface may naturally look very slightly different
from the screenshots, but this difference will be minimal and shouldn’t cause any
confusion.

Acknowledgments
My thanks go first and foremost to the people at O’Reilly Media who have made writ‐
ing a book so delightfully easy: Rachel Roumeliotis, Sarah Schneider, Kristen Brown,
Dan Fauxsmith, Adam Witwer, and Sanders Kleinfeld come particularly to mind.
And let’s not forget my first and long-standing editor, Brian Jepson, whose influence
is present throughout.
As in the past, I have been greatly aided by some fantastic software, whose excellences
I have appreciated at every moment of the process of writing this book. I should like
to mention, in particular:

• git (http://git-scm.com)
• SourceTree (http://www.sourcetreeapp.com)
• TextMate (http://macromates.com)
• AsciiDoc (http://www.methods.co.nz/asciidoc)
• Asciidoctor (http://asciidoctor.org)
• BBEdit (http://barebones.com/products/bbedit/)
• EasyFind (http://www.devontechnologies.com/products/freeware.html)

Preface | xvii
• Snapz Pro X (http://www.ambrosiasw.com)
• GraphicConverter (http://www.lemkesoft.com)
• OmniGraffle (http://www.omnigroup.com)

The book was typed and edited entirely on my faithful Unicomp Model M keyboard
(http://pckeyboard.com), without which I could never have done so much writing over
so long a period so painlessly. For more about my physical work environment, see
http://matt.neuburg.usesthis.com.

From the Programming iOS 4 Preface


A programming framework has a kind of personality, an overall flavor that provides
an insight into the goals and mindset of those who created it. When I first encoun‐
tered Cocoa Touch, my assessment of its personality was: “Wow, the people who
wrote this are really clever!” On the one hand, the number of built-in interface
objects was severely and deliberately limited; on the other hand, the power and flexi‐
bility of some of those objects, especially such things as UITableView, was greatly
enhanced over their OS X counterparts. Even more important, Apple created a partic‐
ularly brilliant way (UIViewController) to help the programmer make entire blocks
of interface come and go and supplant one another in a controlled, hierarchical man‐
ner, thus allowing that tiny iPhone display to unfold virtually into multiple interface
worlds within a single app without the user becoming lost or confused.
The popularity of the iPhone, with its largely free or very inexpensive apps, and the
subsequent popularity of the iPad, have brought and will continue to bring into the
fold many new programmers who see programming for these devices as worthwhile
and doable, even though they may not have felt the same way about OS X. Apple’s
own annual WWDC developer conventions have reflected this trend, with their
emphasis shifted from OS X to iOS instruction.
The widespread eagerness to program iOS, however, though delightful on the one
hand, has also fostered a certain tendency to try to run without first learning to walk.
iOS gives the programmer mighty powers that can seem as limitless as imagination
itself, but it also has fundamentals. I often see questions online from programmers
who are evidently deep into the creation of some interesting app, but who are stymied
in a way that reveals quite clearly that they are unfamiliar with the basics of the very
world in which they are so happily cavorting.
It is this state of affairs that has motivated me to write this book, which is intended to
ground the reader in the fundamentals of iOS. I love Cocoa and have long wished to
write about it, but it is iOS and its popularity that has given me a proximate excuse to
do so. Here I have attempted to marshal and expound, in what I hope is a pedagogi‐
cally helpful and instructive yet ruthlessly Euclidean and logical order, the principles

xviii | Preface
and elements on which sound iOS programming rests. My hope, as with my previous
books, is that you will both read this book cover to cover (learning something new
often enough to keep you turning the pages) and keep it by you as a handy reference.
This book is not intended to disparage Apple’s own documentation and example
projects. They are wonderful resources and have become more wonderful as time
goes on. I have depended heavily on them in the preparation of this book. But I also
find that they don’t fulfill the same function as a reasoned, ordered presentation of
the facts. The online documentation must make assumptions as to how much you
already know; it can’t guarantee that you’ll approach it in a given order. And online
documentation is more suitable to reference than to instruction. A fully written
example, no matter how well commented, is difficult to follow; it demonstrates, but it
does not teach.
A book, on the other hand, has numbered chapters and sequential pages; I can
assume you know views before you know view controllers for the simple reason that
Part I precedes Part II. And along with facts, I also bring to the table a degree of expe‐
rience, which I try to communicate to you. Throughout this book you’ll find me
referring to “common beginner mistakes”; in most cases, these are mistakes that I
have made myself, in addition to seeing others make them. I try to tell you what the
pitfalls are because I assume that, in the course of things, you will otherwise fall into
them just as naturally as I did as I was learning. You’ll also see me construct many
examples piece by piece or extract and explain just one tiny portion of a larger app. It
is not a massive finished program that teaches programming, but an exposition of the
thought process that developed that program. It is this thought process, more than
anything else, that I hope you will gain from reading this book.

Conventions Used in This Book


The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program ele‐
ments such as variable or function names, databases, data types, environment
variables, statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.

Preface | xix
This element signifies a tip or suggestion.

This element signifies a general note.

This element indicates a warning or caution.

Using Code Examples


Supplemental material (code examples, exercises, etc.) is available for download at
http://github.com/mattneub/Programming-iOS-Book-Examples.
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not
need to contact us for permission unless you’re reproducing a significant portion of
the code. For example, writing a program that uses several chunks of code from this
book does not require permission. Selling or distributing a CD-ROM of examples
from O’Reilly books does require permission. Answering a question by citing this
book and quoting example code does not require permission. Incorporating a signifi‐
cant amount of example code from this book into your product’s documentation does
require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “iOS 11 Programming Fundamentals
with Swift by Matt Neuburg (O’Reilly). Copyright 2018 Matt Neuburg,
978-1-491-99931-8.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.

Safari® Books Online


Safari Books Online is an on-demand digital library that
delivers expert content in both book and video form from
the world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research,
problem solving, learning, and certification training.

xx | Preface
Safari Books Online offers a range of plans and pricing for enterprise, government,
education, and individuals.
Members have access to thousands of books, training videos, and prepublication
manuscripts in one fully searchable database from publishers like O’Reilly Media,
Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que,
Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kauf‐
mann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders,
McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more
information about Safari Books Online, please visit us online.

How to Contact Us
Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.


1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/ios11-prog-fundamentals.
To comment or ask technical questions about this book, send email to bookques‐
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia

Preface | xxi
PART I
Language

This part of the book teaches the Swift language, from the ground up. The descrip‐
tion is rigorous and orderly. Here you’ll become sufficiently conversant with Swift to
be comfortable with it, so that you can proceed to the practical business of actual
programming.

• Chapter 1 surveys the structure of a Swift program, both physically and concep‐
tually. You’ll learn how Swift code files are organized, and you’ll be introduced to
the most important underlying concepts of the object-oriented Swift language:
variables and functions, scopes and namespaces, object types and their instances.
• Chapter 2 explores Swift functions. We start with the basics of how functions are
declared and called; then we discuss parameters — external parameter names,
default parameters, and variadic parameters. Then we dive deep into the power
of Swift functions, with an explanation of functions inside functions, functions as
first-class values, anonymous functions, functions as closures, curried functions,
and function references and selectors.
• Chapter 3 starts with Swift variables — their scope and lifetime, and how they are
declared and initialized, along with features such as computed variables and set‐
ter observers. Then some important built-in Swift types are introduced, includ‐
ing Booleans, numbers, strings, ranges, tuples, and Optionals.
• Chapter 4 is all about Swift object types — classes, structs, and enums. It explains
how these three object types work, and how you declare, instantiate, and use
them. Then it proceeds to polymorphism and casting, protocols, generics, and
extensions. The chapter concludes with a discussion of Swift’s umbrella types,
such as Any and AnyObject, and collection types — Array, Dictionary, and Set
(including option sets).
• Chapter 5 is a miscellany. We start with Swift’s flow control structures for branch‐
ing, looping, and jumping, including error handling. Then I discuss a new Swift 4
feature, key paths, and explain to create your own Swift operators. The chapter
concludes by describing Swift access control (privacy), introspection (reflection),
and memory management.
CHAPTER 1
The Architecture of Swift

It will be useful at the outset for you to have a general sense of how the Swift language
is constructed and what a Swift-based iOS program looks like. This chapter will sur‐
vey the overall architecture and nature of the Swift language. Subsequent chapters
will fill in the details.

Ground of Being
A complete Swift command is a statement. A Swift text file consists of multiple lines
of text. Line breaks are meaningful. The typical layout of a program is one statement,
one line:
print("hello")
print("world")

(The print command provides instant feedback in the Xcode console.)


You can combine more than one statement on a line, but then you need to put a
semicolon between them:
print("hello"); print("world")
You are free to put a semicolon at the end of a statement that is last or alone on its
line, but no one ever does (except out of habit, because C and Objective-C require the
semicolon):
print("hello");
print("world");
Conversely, a single statement can be broken into multiple lines, in order to prevent
long statements from becoming long lines. But you should try to do this at sensible
places so as not to confuse Swift. For example, after an opening parenthesis is a good
place:

3
print(
"world")
Comments are everything after two slashes in a line (so-called C++-style comments):
print("world") // this is a comment, so Swift ignores it

You can also enclose comments in /*...*/, as in C. Unlike C, C-style comments can
be nested.
Many constructs in Swift use curly braces as delimiters:
class Dog {
func bark() {
print("woof")
}
}
By convention, the contents of curly braces are preceded and followed by line breaks
and are indented for clarity, as shown in the preceding code. Xcode will help impose
this convention, but the truth is that Swift doesn’t care, and layouts like this are legal
(and are sometimes more convenient):
class Dog { func bark() { print("woof") }}
Swift is a compiled language. This means that your code must build — passing
through the compiler and being turned from text into some lower-level form that a
computer can understand — before it can run and actually do the things it says to do.
The Swift compiler is very strict; in the course of writing a program, you will often try
to build and run, only to discover that you can’t even build in the first place, because
the compiler will flag some error, which you will have to fix if you want the code to
run. Less often, the compiler will let you off with a warning; the code can run, but in
general you should take warnings seriously and fix whatever they are telling you
about. The strictness of the compiler is one of Swift’s greatest strengths, and provides
your code with a large measure of audited correctness even before it ever starts run‐
ning.

The Swift compiler’s error and warning messages range from the insightful to the
obtuse to the downright misleading. You will often know that something is wrong
with a line of code, but the Swift compiler will not be telling you clearly exactly
what is wrong or even where in the line to focus your attention. My advice in
these situations is to pull the line apart into several lines of simpler code until you
reach a point where you can guess what the issue is. Try to love the compiler
despite the occasional unhelpful nature of its messages. Remember, it knows
more than you do, even if it is sometimes rather inarticulate about its knowledge.

4 | Chapter 1: The Architecture of Swift


Everything Is an Object?
In Swift, “everything is an object.” That’s a boast common to various modern object-
oriented languages, but what does it mean? Well, that depends on what you mean by
“object” — and what you mean by “everything.”
Let’s start by stipulating that an object, roughly speaking, is something you can send a
message to. A message, roughly speaking, is an imperative instruction. For example,
you can give commands to a dog: “Bark!” “Sit!” In this analogy, those phrases are
messages, and the dog is the object to which you are sending those messages.
In Swift, the syntax of message-sending is dot-notation. We start with the object; then
there’s a dot (a period); then there’s the message. (Some messages are also followed by
parentheses, but ignore them for now; the full syntax of message-sending is one of
those details we’ll be filling in later.) This is valid Swift syntax:
fido.bark()
rover.sit()
The idea of everything being an object is a way of suggesting that even “primitive” lin‐
guistic entities can be sent messages. Take, for example, 1. It appears to be a literal
digit and no more. It will not surprise you, if you’ve ever used any programming lan‐
guage, that you can say things like this in Swift:
let sum = 1 + 2

But it is surprising to find that 1 can be followed by a dot and a message. This is legal
and meaningful in Swift (don’t worry about what it actually means):
let s = 1.description

But we can go further. Return to that innocent-looking 1 + 2 from our earlier code.
It turns out that this is actually a kind of syntactic trickery, a convenient way of
expressing and hiding what’s really going on. Just as 1 is actually an object, + is
actually a message; but it’s a message with special syntax (operator syntax). In Swift,
every noun is an object, and every verb is a message.
Perhaps the ultimate acid test for whether something is an object in Swift is whether
you can modify it. An object type can be extended in Swift, meaning that you can
define your own messages on that type. For example, you can’t normally send the say-
Hello message to a number. But you can change a number type so that you can:
extension Int {
func sayHello() {
print("Hello, I'm \(self)")
}
}
1.sayHello() // outputs: "Hello, I'm 1"

Everything Is an Object? | 5
Discovering Diverse Content Through
Random Scribd Documents
“Slow down,” she managed to gasp, “I can’t talk to you when you
drive so fast.”
He obediently slowed the car down.
“I can promise you some exciting times when my friend Roy Purvis
gets here,” he said after a long silence.
“Roy Purvis,” she repeated after him, “I never heard you mention
that name before.”
“He is an old friend of mine and we used to race together before he
went in for aviation. He promised me just before I left New York that
he would visit me out here.”
Little did they know what a thrilling part Roy Purvis and his airplane
was to play in their future lives.
The girl was deeply interested in what Mason had told her.
“That will be jolly fun,” her eyes were keenly enthusiastic. “I have
never seen an airplane, I hope he comes soon.”
Mason nodded.
“Roy is very eccentric, and I wouldn’t be surprised to see him out
here any time.”
On the way home he stopped the car and let Josephine take his seat
while he instructed her in driving. Soon she was driving the racer
almost as skillfully as he.
After about an hour she became tired and he relieved her at the
wheel.
“You have accomplished wonders with your first lesson,” he told her
with honest conviction in his voice. “I am truly proud of you.”
“I am very glad you think so, and if you will take me out again some
time, I think I can do still better.” He fancied there was just the
suspicion of an appeal in her voice.
“The pleasure will be all mine,” he answered gallantly.
They were nearing the ranch now, and just as they rode past the
corral they were surprised to see MacNutt throwing a blanket over
his sweat-reeked horse.
Apparently he had ridden faster and by taking a shorter route had
arrived just ahead of them.
CHAPTER IX—MYSTERIOUS MACNUTT

The following morning, and before anybody was astir at Bar X ranch,
the form of a man emerged from the bunkhouse and looking
cautiously around to make sure that no one was watching him,
stealing silently to the corral, he quickly roped and saddled one of
the horses. It was MacNutt, and had any of the cowboys seen his
face at that moment they would have been amazed. All trace of the
half-wit smile had vanished, and in place of the drooping shoulders
and shambling gait that had been characteristic of the man, he now
moved with the cunning and quickness of a panther.
As his supple body shot into the saddle a pair of revolver butts were
exposed to view for an instant. Whatever MacNutt’s mission was, the
man was going heavily armed. He rode leisurely as though fearful
the noise of his horse’s hoofbeats might strike the ears of some early
prowler of the ranch.
When well clear of the outbuildings of the ranch he gave his horse
free rein, riding with all the ease and grace of a cowboy. Ten miles
from Bar X ranch the trail divided. One trail led to Trader’s Post and
the other to Ricker’s ranch.
When MacNutt came to this point, he chose the trail leading to the
Ricker ranch!
A grim smile spread over the man’s face.
“I don’t suppose it was necessary for me to sneak out in this
fashion,” he spoke softly to his horse, “none of the Bar X outfit take
me seriously, only young Mason. I will have to watch out for him,
he’s liable to spoil my plans.”
His face grew dark and ominous at the thought. Having a fresh
mount he pressed the horse on relentlessly as though to reach the
ranch in time to keep an appointment. Time and distance passed
swiftly beneath his horse’s pounding hoofs, and when within a few
miles of Ricker’s ranch he carefully examined his guns to see if they
were in good working order.
As he drew near Ricker’s ranch his tense muscles relaxed, the half-
wit smile appeared and with it the awkward poise and drooping
shoulders of the man MacNutt. Although he did not know it, his
movements had been watched by a guard placed by Ricker.
This man swept the plains with field glasses and word was quickly
sent to Ricker by the guard for instructions. He was promptly
ordered to hold the rider up at any cost. Since the last time Ricker
had been visited by the cowboys of the Bar X ranch, he swore an
oath that no more of them should pass farther than a given spot and
that was where he had placed the guard.
Ricker had picked a good man for the job, for when he was in a
quandary as to who should hold the post, his eyes fell on one of his
cowboys, Tug Conners by name, and he was placed about a hundred
yards from the ranch where he could command a view of the plains
in all directions.
Tug Conners was a daredevil and desperado who would shoot first
and ask questions afterwards, and it was to this man that MacNutt
would have to pass muster. The guard set himself and studied the
rider through his glasses. The watcher swore softly. The slow gait of
the horse and its rider’s awkward position in the saddle had him
puzzled.
Twice he raised the rifle at his side and covered the stranger, only to
lower it each time in disgust. Seizing the glasses again he tried to
make out who the stranger was. An exclamation burst from his lips,
for this time he had a close view of the rider.
“Well, I’ll be damned!” he swore furiously, “I remember that freak,
he was with the sheriff when they made that call on Ricker. He looks
like a damn fool and acts the part. Wonder what the tenderfoot can
want here?”
Tug was bitterly disappointed as he had hoped the rider would prove
to be one of the sheriff’s cowboys, and he would have started
trouble with any of them at the slightest provocation. He hated them
all intensely, but with this fellow it was different.
Tug couldn’t bring himself to pick trouble with a half-wit, so he
determined to throw a scare into him and run him off the ranch.
He was crouched behind a small mound and as MacNutt came
abreast his place of concealment he sprang up and covered him with
his rifle.
“Stretch your arms!” Tug commanded him, his eyes glittering
savagely, “I reckon this is about your limit. Who let you out,
anyway?”
MacNutt’s hands went up with alacrity, and such a look of dismay
spread over his features that he brought a grin to Tug’s face.
“Get down off that horse,” he next commanded him, keeping the
rifle on a line with his heart.
“Don’t keep that cannon pointed at me, it makes me nervous,”
protested MacNutt in a trembling voice as he laboriously
dismounted.
“Oh, the gun makes you nervous, does it, tenderfoot?” Tug sneered
with bitter sarcasm. “Well, it will go off mighty sudden if you don’t
answer my questions right smart. You’re from Bar X, ain’t you? Who
sent you here, and what do you want?”
MacNutt had apparently found his nerve again, the foolish smile
appearing on his face.
“You fire your questions too fast,” he protested in his droll voice, and
started to lower his hands.
“Keep ’em up!” his captor snarled, raising his gun threateningly.
MacNutt smiled at Tug blandly, his hands held high in the air.
“I rode over from the ranch to see one of Ricker’s men,” he
explained with childlike simplicity. “Met him at the Post yesterday. He
ain’t got no more use for the Bar X outfit than I have, and I agreed
to put him wise to some things I know about them.”
Tug stared at him incredulously.
“What is the name of the cowboy you met yesterday?” he
questioned, suspicion in his voice.
“I can’t remember his name,” MacNutt replied readily. “We were
slopped up a little, but I can describe him.” This he proceeded to do,
and evidently to Tug’s satisfaction.
“You mean Jean Barry,” he said in a modified tone when MacNutt
had finished his description. “Come, and I’ll take you to him.”
A curious gleam shone in MacNutt’s eyes for an instant, as he was
ordered by Tug to keep six paces in advance of him. On the way to
the ranch house, a close observer would have noticed that not a
single item of the plans of the buildings or out-houses of the ranch
had escaped MacNutt’s notice. Although his eyes held their dull
sleepy look, they sought out every object of importance. A group of
cowboys were watching the approach and one of them walked out
rapidly to meet them. He proved to be Ricker.
“What have we here, Tug?” he demanded, with a suspicious look at
MacNutt.
“Claims he knows Jean Barry and wants to see him,” Tug answered
tersely.
Ricker scowled darkly.
“Jean is down to the corral. Go get him and see if he knows this
fellow,” he ordered Tug, while watching MacNutt sharply.
Tug soon returned in company with a cowboy.
“Jean, do you know this man?” Ricker question with a wave of his
hand toward MacNutt.
“Shore, I know him, he’s all right,” the man Jean answered without
an instant’s hesitation.
Ricker looked immensely relieved.
“All right, take him to the ranch and make him acquainted with the
boys. I’ll hold you responsible for him. We are going to have rifle
and revolver practice in a few minutes, maybe your friend would like
to join us,” he said, addressing Jean and giving MacNutt another
sharp look.
Just a fleeting gleam came into MacNutt’s eyes as he readily
consented to join them. He was conducted to the ranch by Jean, Tug
having gone back to his post. At the ranch he was presented to
Waneda the Spanish girl and to the cook, an old Negress. It was his
first opportunity to see Waneda at close range, and he studied her
face intently although seemingly interested in what Jean was telling
him about the target practice.
Finally Jean left him alone with the two women after saying he was
going to help set up targets, and would let him know when they
were ready.
MacNutt immediately drew the girl into a conversation after making
sure he had nothing to fear from the old Negress, she being quite
deaf. MacNutt had again thrown off his assumed role of a half-wit
and was alert and thinking rapidly. The girl had noticed the change,
and shrank back against the wall staring at him dumbly.
“I know you are a good girl, Waneda,” he was saying rapidly and in a
low voice, “I can generally size a person up at first glance, and you
have a good face. Now, I wish to clear my mind on one point: did
you know the contents of the note you delivered to the Bar X ranch
that sent the cowboys into the mountains after Powers and the half-
breed?”
“No,” she answered guardedly, her eyes searching his face, eager to
read his thoughts.
His face grew stern.
“I was almost sure of it, but your answer proves that point,” he said
kindly, “still, that very note came near getting some good men killed.
You like young Mason, don’t you?”
A startled cry escaped her lips. With a quick move she seized him by
the arm.
“I love him! Is he in danger? Speak quick!”
MacNutt gently released her hold and placed a chair for her.
“Steady, girl,” he warned her; “no, he’s not in danger just now, but
you are. This is no place for you, and I am going to get you out of
here, but before that time comes you must help also, and in doing
that you will be helping Mason, too.
“There’s going to be hell brewing around here before long. What do
you suppose Ricker has that guard out there for? And this target
shoot is for a purpose, too. I think I can trust you not to betray me,
and you also will be able to prove your loyalty to Mason and wipe
out the damage you caused by carrying that note.”
The girl was thoroughly aroused now.
“Who are you?” she demanded, her breath coming in quick gasps.
“If Ricker finds out that you are against him, your life wouldn’t be
worth a plugged nickel!”
Jean Barry hurriedly entered the room at this moment and
interrupted his talk with the girl. A lightning glance of understanding
passed between the two men.
“I’ll be with you in a few minutes and join the men at the shoot,”
MacNutt said rapidly in answer to an inquiring look from his friend.
Jean nodded, and was gone in the same hurried manner that he had
entered the room.
MacNutt turned and looked gravely at the girl.
“Who are you?” she repeated impatiently.
“Your friend,” he answered earnestly; “that is all I can tell you at
present, but you must trust me implicitly. Just go on here as before,
and if Jean Barry tells you to leave this place at a certain time you
must obey him, for he is working with me. If Jean comes to you for
any information, give it to him if you can without causing suspicion.
You will be helping me and Mason. I can trust you in this, can’t I?”
“You are a strange man,” she answered slowly, “but somehow I have
confidence in you. I feel that this ranch is uncanny, and things are
not as they should be. At night I hear strange sounds and men come
and go at all hours. I am afraid of the men and especially of Ricker;
he wants me to marry him and I hate him. The old Negress here has
protected me from him many a time when he had been drinking. I
wanted to leave here long ago, but I am afraid to leave for Ricker
would find me again, and then even the Negress couldn’t save me.
He is terrible when he is in a rage and the cowboys fear him too, for
he is a dead shot and none of them would have a chance with him.
I’ll trust you and do as you say.”
She had crept close to him while talking and her face was deathly
pale.
Something like an oath escaped from MacNutt’s lips.
“Be brave,” he said, speaking earnestly. “It won’t be but a few weeks
now before I will have you out of here, and maybe in a few days.
Ricker is engaged in some lawless business besides mere cattle
raising. He has a collection of the worst crooks in the country about
him, and I mean to get to the bottom of his game.”
After saying a few more words of comfort to the girl, MacNutt
strolled leisurely out and joined the party near the targets.
He had again assumed his slouching gait and halfwit smile. He was
greeted indifferently by the cowboys, save by Ricker, who was again
regarding him sharply. MacNutt returned the stare with his usual
good-natured grin, while engaging Jean Barry in conversation.
“Watch sharp!” Jean Barry cautioned him.
“Ricker seems to suspect you for some reason and may put you to a
severe test.”
MacNutt nodded and inclined his head slightly, as he noticed Ricker
call one of his cowboys over to him. The man called by Ricker was
his foreman, Jim Haley, the most expert shot on the ranch with the
exception of Ricker himself. A low conversation took place between
the two men.
“Jim, how long has Jean Barry been with us?” Ricker demanded of
his foreman.
Tall and muscular, with deep cruel lines written on his face, Jim
Haley the foreman turned and looked at the man in question.
“Oh, about a month, I reckon,” he replied, glancing quizzically at his
chief.
The answer set Ricker’s brows to knitting.
“Jim, I want you to watch Jean Barry,” he said sharply, as though
coming to a sudden decision. “He’s the last man we took on and
hasn’t been with us long enough to be trusted too far. As for this
man MacNutt, keep your eye on him also. He claimed to the guard
that he isn’t friendly with the Bar X outfit and has a grievance
against them. I can’t just make him out, and I want you to trail him
after he leaves here and find out just what his standing is at Bar X.
Jean took up with him mighty sudden, and I don’t like the looks of it.
Look sharp now, and make your report to me in the morning.”
At the curt dismissal Jim Haley moved off while his chief mingled
with the men and directed the rules of the target practice. MacNutt
was ignorant of what had taken place and was calmly looking his
guns over.
Jean Barry pressed close to him at this moment.
“Watch out for Jim Haley, the man that Ricker was just talking to,”
he hissed in his ear.
MacNutt made no answer to his friend’s warning as the shoot had
now commenced. The first contestants were leading off with
revolver practice. The targets were set at seventy-five yards and
each man was to fire six shots apiece. The men fired in turn, each
scoring fair hits, until Ricker and Jim Haley’s turn came. When they
had fired six shots apiece it was seen that they had each scored
bull’s-eyes, and both had one shot on the extreme edge of the bull’s-
eye. Ricker looked at his foreman.
“Guess we’ve got to shoot this one over, Jim,” he called, a trifle
nettled.
He was conceded the best shot on the ranch, and it bothered his
vanity to have his mark equalled. The marker was closely examining
the targets.
“A tie,” he finally announced.
“Put up fresh targets, Jim, and I will shoot off the tie,” Ricker
ordered briskly, “and put up another one; we’ll have our friend
MacNutt here try his skill with us.”
Ricker and Jim shot their tie off, the former winning this time by a
large margin.
Ricker smiled sarcastically at MacNutt as the latter stepped up in his
awkward way to take a position. A titter ran through the group of
cowboys as they watched his odd movements. He was likely to prove
a source of amusement for them after all.
Ricker suddenly stepped forward.
“Come on, Jim, you and I will set a high record for him. We’ll show
him some shooting that will make him go some,” he boasted.
Jim Haley led off, scoring almost the same hits as before.
“You must have your shooting eye with you today, Jim,” Ricker
remarked as he took his position.
Then he put six bullets in the bull’s-eye, firing with a precision that
was perfect.
“I’ll bet none of the Bar X outfit can equal that,” he boasted to
MacNutt with a cynical smile.
MacNutt still wore his good-natured grin.
“Maybe not,” he drawled, “but I ain’t shot yet.”
A howl of derision went up from the cowboys.
“Go ahead and shoot, you tenderfoot,” one of them yelled.
Suddenly MacNutt’s hand went up, and he fired six shots in rapid
succession; so rapid was the fire that the reports blended together.
All the cowboys were grinning broadly, for it looked as though
MacNutt had fired at random. Their faces took on a look of wonder,
however, when it was seen that the marker was examining the
target with extreme care.
“All bull’s-eyes!” he announced as though completely mystified.
Ricker swore roughly.
“Come on, Jim,” he called out impatiently, “that marker’s eyes must
be off.”
There was a general rush for the targets, and an exclamation of
admiration went up from the cowboys when it was seen that
MacNutt’s bullets were grouped closer to the center of the bull’s-eye
than were Ricker’s.
“He’s a freak,” Jim Haley spoke up sullenly.
“Where did you learn to shoot like that?” Ricker questioned MacNutt
sharply. “Can you do as well with a rifle at two hundred yards?”
MacNutt grinned modestly.
“I reckon I can,” he drawled slowly. “I’ve shot a revolver and rifle
ever since I was a kid.”
A rifle shoot was next in progress, but MacNutt declined to wait for
that event. Soon, he took his leave after saying a few words in an
undertone to his friend Jean Barry. The cowboys watched him depart
with keen interest. He had risen several points in their estimation by
his accurate shooting.
As he drew near the place where Tug Conners had held him up, he
saw the guard leaning on his rifle, watching him approach.
“Guess I can pass you through quicker next time you visit us,” Tug
called after him as he rode past. “If you see one of our men at the
Post, tell him to hurry up for I sent him to bring me some tobacco.”
“I sure will,” he answered cheerfully. “I am going back that way and
if I see your man I’ll hustle him along.”
“Yes, you certainly will pass me through quicker when I call on you
next time, my friend,” he added grimly to himself as he rode steadily
on.
In due time he arrived at the Post, where he spent about two hours
looking after some private business and making a few necessary
purchases. As he mounted his horse for the run to Bar X he was
surprised to see Jim Haley lounging on the hotel veranda.
“He must have followed me,” he mused, a grin playing over his
features. “The play is on in earnest.”
He looked around to see if the cowboy’s horse was in sight. Seeing
no signs of the animal he decided that the cowboy had put his horse
in the hotel corral.
MacNutt soon forgot the incident and riding fast he arrived at Bar X
before nightfall.
The first person he encountered after putting his horse up was
Mason.
Mason looked at him with accusing eyes.
“MacNutt,” he began, “I want to have a quiet little talk with you. I
haven’t as yet said anything to anybody else, but it looks to me as if
you are trying to play a double game. Yesterday, I saw you talking in
very friendly terms with one of the cowboys from the Ricker ranch.
Several other little things have happened since you came here that
have made me suspicious of you. You know these are troublesome
times. I want to ask you point blank, are you with us, or do you
stand with the Ricker faction?”
MacNutt had listened passively while Mason was talking. He seemed
deeply moved.
“I know these are troublesome times as you say,” he replied
earnestly, “but I want you to trust me a little longer and then I will
show you something that will surprise you. I am here for a good
purpose and am working for the interest of the Bar X people and you
in particular. I take you to be a man of sound judgment and give you
my word of honor that I am working here for a good cause. In due
time I will explain everything that appears mysterious to you just
now, and I want you to have faith in me. Is that satisfactory to you?”
“I suppose it will have to be,” Mason answered, completely
mystified.
CHAPTER X—WELCOME VISITORS

Two days later unusual scenes of activity took place at Bar X ranch.
There was a general brightening and cleaning up about the place.
Cowboys were industriously cleaning horses and polishing saddle
accoutrements. The ranch-house was being vigorously cleaned and
aired. The reason for all this extra work was a telegram that Mason
was reading for perhaps the hundredth time. He whistled gaily as he
thrust the telegram back in his pocket and started to tune up his
racing car.
The day before, Scotty had ridden in from the Post with a telegram
for Mason. When he read its contents he gave a cry of delight. It
was from his sister and stated that she was coming with his mother
to pay him a visit and they were bringing along a friend of the family
for company. The telegram had been dispatched from a town where
the party had a stopover and Mason hastily consulting a time-table
found that they would arrive at the Post the next day.
The good news had banished all thoughts of MacNutt and his
strange actions from his mind.
Scotty had immediately been sent back to the Post to await their
arrival.
Mason had broken the news to Josephine and they planned to drive
the car to Trader’s Post early the next morning. The girl’s face was
all aglow at the prospect of meeting his folks. She had assumed
command of the ranch, making the cook brighten up about the
bunk-house and mess-room while giving orders to the cowboys
about their general unclean appearance that made them gasp in
wonder. Mason had come in for his share of the cleaning-up process
and after seeing the entire ranch force set in motion, he meekly
submitted.
So the next morning after an almost sleepless night found him hard
at work on his racing car. He was so deeply interested in his work
that he didn’t hear a light step near him until a subdued ripple of
laughter caused him to look up in surprise. The mistress of the ranch
stood before him and was regarding him with a look of approval. He
made her a profound bow.
“Oh, most charming slave-driver, does my work please the little
Princess?” he questioned her with mock humility.
Her eyes held him with a smile.
“The machine certainly looks more presentable,” she returned in the
same light vein.
She gave the car another sharp appraising look, and glanced at him.
“And you look as though you had tried to clean it, from the
appearance of your face and those dirty overalls,” she added.
The smile had cropped out again and with it the appearance of the
pretty dimples he secretly adored.
“I confess I do look like a coal heaver,” he said, starting up briskly,
“but I’ve had the engine running like a top and it is in fine shape. I
will have these duds off and be cleaned up in about a minute. Please
run along now, Josephine, and get ready. I will drive right up to the
house for you.”
Josephine had already started for the house.
“I will be ready and waiting for you, Sir Jack,” she called back to him
as he stood watching her trim figure until she disappeared in the
house.
Five minutes later Mason was speeding along the trail with
Josephine beside him in the low seat of his powerful racer. She was
in high spirits as usual, but seemed to be in a meditative mood. He
stole a glance at her to find her eyes searching his face with an odd
expression in them.
“I am puzzled and curious to see that third party my sister is
bringing with her,” he said, breaking a long silence.
She nodded.
“I was thinking of about the same thing. I hope your mother and
sister will like me,” she said wistfully.
He laughed outright.
“So, that is what you are worrying your pretty head about. Well, I
will answer for mother, and as for sis, she will take to you like a duck
does to water.”
“Do you really think so?” there was a little catch to her voice.
“I know so.” There was a positive ring to his voice.
Josephine looked pleased.
“I am glad to hear you say that. I was afraid your sister would be
such a fine lady and wear such grand clothes that I would appear
like a savage to her, and you know we are kind of wild and woolly
out here.”
“Well, you will get the surprise of your young life, then,” he declared.
“Sis is athletic, and plays tennis and baseball just the same as I do,
and I know you two will be chums from the minute you meet.”
Josephine was silent in thought, but he could see there was a
pleased look on her face. They had been making fast time, and
already the outbuildings of Trader’s Post were plainly visible.
A few minutes later Mason drove into the town and stopping at the
hotel inquired for Scotty. He was informed that Scotty had left an
hour ago for the small station four miles distant, as the train was
about due. Scotty had put up at the hotel over night and naturally
would be fresh for the long trip back to the ranch. His wagon would
accommodate four people, and the plan was to have Mason’s mother
and the mysterious third party ride to the ranch with Scotty while
Mason was to take his sister and Josephine in his car. Mason broke
all speed limits for the four miles, and when they drove up to the
small station in a cloud of dust, Scotty waved at them from the
platform. He was grinning broadly, and Mason was keenly amused
when Josephine hastened over and surveyed him critically. There
was a pleased smile on her face.
“Scotty, I see that you have obeyed my instructions and haven’t
drunk anything,” she said kindly, while shaking his hand.
“Nope,” he answered, beaming on her. “I reckon a man would be
plumb crazy that didn’t try to please you.”
“You won’t lose anything by doing as I want you to, Scotty. Oh, I
hear the whistle of the train!”
She seized Mason by the arm and they took a position on the
platform. There was the same old stage that had carried him to
Trader’s Post, and the same talkative driver. Mason peered anxiously
as the train came to a stop with a shrieking and grinding of brakes,
and as the passengers began to get off, he strode forward eagerly as
he made out the familiar face of his sister Ethel. She caught sight of
him at the same instant.
“Jack!” she gasped, as he nearly swung her off her feet.
“Where is mother?” he demanded, holding her at arm’s length.
“Right behind you, stupid,” she managed to say when she had got
her breath back. “And allow me to introduce Mr. Percy Vanderpool.”
Mason kissed his mother and turned to acknowledge the
introduction. Percy Vanderpool. Then his eyes twinkled and he had
to force back a laugh of merriment.
So this was the third party. Percy was a fop, but he came from a
very aristocratic family. Mason had known of him through some of
the New York clubs which he held membership in. He had nothing
against the fellow, only his fondness to ape English ways and wear
loud clothes.
Percy was dressed in a loud checkered suit and Mason grinned in his
face as he shook hands. His hand had a decided feminine touch and
Mason chuckled as he thought of the amusement he would provide
for the cowboys. Josephine had held back, but now Mason caught
her hand and drew her into the group.
“Mother, I wish to introduce you and sis to a real Western girl, Miss
Josephine Walters,” he said.
Ethel put her arms around Josephine and kissed her. “I feel that I
have known you for a long time, dear,” she said sweetly. “Jack has
written home about you in all his letters and urged me to visit you.”
Josephine’s face was radiant, while she could only stammer a few
words as she was introduced to Mason’s mother and Percy
Vanderpool. Mason took the situation in hand by rounding up Scotty
and introducing him to his folks. The cowboy stood fingering his hat
while his face grew red with embarrassment.
He shifted his feet awkwardly as Mason introduced him to Percy
Vanderpool and Mason tried hard to keep back a smile when he
noticed a blank look spread over the cowboy’s face as he sized Percy
up.
Ethel soon put the cowboy at ease by chatting with him in her
friendly way, and won his eternal friendship by praising up Nevada
climate and the healthy condition of her brother Jack.
“Break away, you two,” Mason cut in with a laugh. “Sis, you will have
Scotty hypnotized in another minute. I have arranged to have you
ride to the ranch with Josephine and myself, while Percy and mother
will ride with Scotty. I know that mother doesn’t like to ride fast, and
I can easily take you in my car. Will that plan suit you, mother?”
“You know it will, son,” she answered.
“Yes,” Ethel said in a bantering tone, “you know that mother never
could get used to your reckless driving, but I’m willing to risk my
neck, and if anything happens you will have two victims to haunt
you.”
“Oh, come now, sis, I’m not as reckless a driver as that,” he
protested, grinning broadly as he noticed a long look on the
cowboy’s face.
Scotty had evidently expected Ethel to ride with him for his face
showed disappointment.
“It seems a shame,” Josephine spoke up, “to go on and leave Mrs.
Mason. Scotty won’t get to the ranch before nightfall. I’ve a notion
to ride with Scotty and keep her company.”
“No, my dear,” Mrs. Mason interposed hastily, “I will enjoy this ride to
the ranch. You young folks go ahead in the car. I will sleep better to-
night after a long ride in the air, as my head aches from riding in
hot, stuffy trains.”
Mason bundled his sister and Josephine into his car.
“You will have plenty of time to reach the ranch before dark, Scotty,”
he called back to the cowboy as he started his racer off with a rush.
They passed through Trader’s Post at a more moderate speed, as
Mason wanted his sister to get a good look at the town.
“It isn’t much of a place,” Josephine confided to Ethel in an
apologetic voice, “but we do about all our trading there.”
“Oh, I think this country is great. I haven’t been away from New
York in a long time and this vacation will do me good,” Ethel
answered enthusiastically.
She looked curiously at her brother.
“Now, what are you grinning about, Jack?” she demanded.
“I was wondering where you picked it up,” he said, his face now
sober as a deacon.
“It, what?” she queried, her eyes wide in astonishment.
“Why, Percy Vanderpool, of course. Did he wish himself on you, or
did you invite him out here? I have seen him at the clubs in New
York, and he was noted for a brainless wonder although he traveled
in the best of society.”
“I was surprised and humiliated by your actions at the station,
brother,” she said reprovingly, “why, you actually laughed in his face.”
“Couldn’t help it,” he confessed ruefully, “Percy is a regular freak,
and I wish you would tell me how he came to be with you and
mother.”
“Don’t be too hard on the poor fellow, Jack,” his sister retorted, “he
was very kind and obliging to us on the trip and we were glad to
have his company on the long ride out here.
“You see, it was this way, his father knows Dad well, and hearing we
were going to Nevada his father asked Dad if he could take the trip
with us. Percy had just recovered from a long illness, and the doctor
ordered a change of climate for him.
“Dad asked us if we cared to have Percy go with us, and we gave
our consent as it is a long trip for two women to take alone. Percy is
really a good fellow, only as you say, he has more money than
brains.
“He intends to stay at the hotel after to-night, but he thought it
would be a bally good chance, as he put it, to see this part of the
country.”
Josephine had been an interested listener.
“We couldn’t think of having Mr. Vanderpool stay at the hotel among
total strangers,” she said warmly, “there is plenty of room at our
ranch, and I think it will be great fun to have him with us.”
“You girls can settle it between yourselves,” Mason ventured with an
air of resignation. “If you are satisfied to have him stay at the ranch
I guess I can stand his company, but the cowboys sure will have fun
with him.”
“Jack, watch where you’re going,” his sister cried, as the car gave a
wide lurch and nearly went off the trail.
He pulled the racer back onto the trail with a master hand and cut
down his speed a trifle.
“Anyone would think that you were jealous of Percy, the way you
talk,” she added, giving Josephine a nudge.
He laughed heartily.
“Come now, sis, don’t accuse me of that; I want something to get
jealous over first.”
A general laugh followed his remark, but the girls could see that he
was a little nettled over his sister’s teasing. Josephine changed the
subject by drawing Ethel’s attention to the nature of the country
they were passing through. The city girl was deeply interested in the
seemingly never ending chain of mountains in the distance, and
expressed her admiration for the beautiful valleys and mountains in
glowing terms. Soon, they fell to talking of city society and the
prevalent fashions in gowns, while Mason turned his attention to
getting more speed out of his motor. A feeling of contentment seized
him now that his sister was with him, and he was positive she would
be able to explain more fully the enmity that existed between his
father and Ricker. It was all a confused muddle to him, and as his
thoughts ran in this channel it put a damper on his spirits. They had
struck a better stretch of road and he turned his attention once
more to the girls at his side. One glance at their smiling faces quickly
dispelled all his gloom. They were nearing the ranch now and
Josephine was pointing out points of interest to the city girl, who
was showing lively interest in everything.
“We are pretty close to home now, girls,” Mason said with a smile, “I
trust you have enjoyed the ride, and have no broken bones?”
“You drove fine, Sir Jack,” Josephine spoke up; “drive right up to the
house and I’ll make your sister acquainted with my folks while you
are putting the car up.”
Mason unloaded his fair passengers at the ranch door after first
promising Josephine to make haste in putting the car up as she
wanted him to accompany them for a brief walk around the ranch.
They were somewhat cramped and lame from the long ride and felt
that a walk would do them good. It was still early in the afternoon
and they would have time to show his sister about the ranch before
Scotty arrived with his passengers. Josephine had asked Ethel as
they were entering the house if she was tired, and the prompt
answer she received to the contrary was proof of Mason’s assertion
that his sister was athletic and strong. Josephine’s heart warmed to
the city girl for she admired strength and ruggedness, she herself
being practically born in the open air.
Her fondest hopes were realized, for here was a girl after her own
heart whom she could make a companion and chum of, and she
intended to keep her at the ranch as long as possible.
Mason was longer than he expected in putting the car away and had
just started for the house when he saw the girls coming out. He
paused in his walk and studied them as they came walking toward
him, life and animation in their stride.
“Beauties, both of them,” he muttered half unconsciously to himself,
“and fine girls whom a man would fight to the death for.”
Both girls were about the same build, Ethel being a trifle heavier.
She was a decided brunette while Josephine was more of the blonde
type. For richness of color the Western girl had the advantage over
the city girl, but both were good to look at.
“And what were you mooning about, Sir Jack?” Josephine challenged
him, when both girls paused in front of him and made a curtsey.
“I’ll never tell you,” he answered, as with a bow he returned their
salute. “You both would have swelled heads, and I refuse to have
two vain girls on my hands.”
Both girls charged at him and insisted that he tell them at once. He
laughingly compromised with them by offering to show them around
the ranch in the short time before his mother should arrive.
Mason first conducted them to the corral, his sister being an admirer
of fine horses, and as they were starting to leave the corral for an
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like