100% found this document useful (1 vote)
33 views

Instant Access to Data Structures and Algorithms in Swift: Implement Stacks, Queues, Dictionaries, and Lists in Your Apps 1st Edition Elshad Karimov ebook Full Chapters

Algorithms

Uploaded by

pryckrohlla
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 (1 vote)
33 views

Instant Access to Data Structures and Algorithms in Swift: Implement Stacks, Queues, Dictionaries, and Lists in Your Apps 1st Edition Elshad Karimov ebook Full Chapters

Algorithms

Uploaded by

pryckrohlla
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/ 55

Download Full Version ebook - Visit ebookmeta.

com

Data Structures and Algorithms in Swift: Implement


Stacks, Queues, Dictionaries, and Lists in Your
Apps 1st Edition Elshad Karimov

https://ebookmeta.com/product/data-structures-and-
algorithms-in-swift-implement-stacks-queues-dictionaries-
and-lists-in-your-apps-1st-edition-elshad-karimov/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmeta.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

Cambridge IGCSE and O Level History Workbook 2C - Depth


Study: the United States, 1919-41 2nd Edition Benjamin
Harrison
https://ebookmeta.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-
benjamin-harrison/
ebookmeta.com

Clojure Data Structures and Algorithms Cookbook 25 recipes


to deeply understand and implement advanced algorithms in
Clojure 1st Edition Rafik Naccache
https://ebookmeta.com/product/clojure-data-structures-and-algorithms-
cookbook-25-recipes-to-deeply-understand-and-implement-advanced-
algorithms-in-clojure-1st-edition-rafik-naccache/
ebookmeta.com

Data Structures & Algorithms in Python John Canning

https://ebookmeta.com/product/data-structures-algorithms-in-python-
john-canning/

ebookmeta.com

New Literacies New Agencies A Brazilian Perspective on


Mindsets Digital Practices and Tools for Social Action In
and Out of School New Literacies and Digital
Epistemologies Eduardo S. Junqueira (Editor)
https://ebookmeta.com/product/new-literacies-new-agencies-a-brazilian-
perspective-on-mindsets-digital-practices-and-tools-for-social-action-
in-and-out-of-school-new-literacies-and-digital-epistemologies-
eduardo-s-junqueira-edit/
ebookmeta.com
Tyrannosaurus Rex Rebecca Sabelko

https://ebookmeta.com/product/tyrannosaurus-rex-rebecca-sabelko/

ebookmeta.com

Savage Steamy Mountain Man Instalove Romance The Men Of


Black Pine Woods Book 5 1st Edition Kelsie Calloway

https://ebookmeta.com/product/savage-steamy-mountain-man-instalove-
romance-the-men-of-black-pine-woods-book-5-1st-edition-kelsie-
calloway/
ebookmeta.com

Phosphor Handbook - Novel Phosphors, Systems and


Applications 3rd Edition Xiaojun Wang

https://ebookmeta.com/product/phosphor-handbook-novel-phosphors-
systems-and-applications-3rd-edition-xiaojun-wang/

ebookmeta.com

Women's Economic Thought in the Romantic Age 1st Edition


Joanna Rostek

https://ebookmeta.com/product/womens-economic-thought-in-the-romantic-
age-1st-edition-joanna-rostek/

ebookmeta.com

Damaged Gods Monsters of Saint Mark s 1 1st Edition Ja


Huss

https://ebookmeta.com/product/damaged-gods-monsters-of-saint-
mark-s-1-1st-edition-ja-huss/

ebookmeta.com
Rousseau The Discourses and Other Early Political Writings
2nd Edition Rousseau

https://ebookmeta.com/product/rousseau-the-discourses-and-other-early-
political-writings-2nd-edition-rousseau/

ebookmeta.com
Data Structures
and Algorithms
in Swif t
Implement Stacks, Queues,
Dictionaries, and Lists in Your Apps

Elshad Karimov

www.allitebooks.com
Data Structures and
Algorithms in Swift
Implement Stacks, Queues,
Dictionaries, and Lists
in Your Apps

Elshad Karimov

www.allitebooks.com
Data Structures and Algorithms in Swift: Implement Stacks, Queues,
Dictionaries, and Lists in Your Apps
Elshad Karimov
New York, New York, USA

ISBN-13 (pbk): 978-1-4842-5768-5 ISBN-13 (electronic): 978-1-4842-5769-2


https://doi.org/10.1007/978-1-4842-5769-2

Copyright © 2020 by Elshad Karimov


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole
or part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical
way, and transmission or information storage and retrieval, electronic adaptation, computer
software, or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a
trademark symbol with every occurrence of a trademarked name, logo, or image we use the
names, logos, and images only in an editorial fashion and to the benefit of the trademark
owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms,
even if they are not identified as such, is not to be taken as an expression of opinion as to
whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the
date of publication, neither the authors nor the editors nor the publisher can accept any
legal responsibility for any errors or omissions that may be made. The publisher makes no
warranty, express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Aaron Black
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201)
348-4505, e-mail [email protected], or visit www.springeronline.com. Apress
Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business
Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit http://www.
apress.com/rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our
Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on GitHub via the book’s product page, located at www.apress.com/
978-1-4842-5768-5. For more detailed information, please visit http://www.apress.com/
source-code.
Printed on acid-free paper

www.allitebooks.com
Table of Contents
About the Author���������������������������������������������������������������������������������xi

About the Technical Reviewer�����������������������������������������������������������xiii

Chapter 1: Arrays����������������������������������������������������������������������������������1
Introduction������������������������������������������������������������������������������������������������1
Main Features of Arrays�����������������������������������������������������������������������������2
Retrieving Elements from an Array������������������������������������������������������������4
Adding Elements to an Array����������������������������������������������������������������������5
Removing Elements from an Array�������������������������������������������������������������6
Built-in Functions and Properties���������������������������������������������������������������6
isEmpty�������������������������������������������������������������������������������������������������6
First and Last����������������������������������������������������������������������������������������7
Reversed and Reverse��������������������������������������������������������������������������7
Count�����������������������������������������������������������������������������������������������������7
Conclusion��������������������������������������������������������������������������������������������������8

Chapter 2: Dictionaries�������������������������������������������������������������������������9
Introduction������������������������������������������������������������������������������������������������9
Accessing Values in a Dictionary��������������������������������������������������������������11
Adding/Modifying to a Dictionary�������������������������������������������������������������13
Removing a Value from a Dictionary��������������������������������������������������������14

iii

www.allitebooks.com
Table of Contents

Built-in Functions and Properties�������������������������������������������������������������14


isEmpty�����������������������������������������������������������������������������������������������14
First�����������������������������������������������������������������������������������������������������14
Count���������������������������������������������������������������������������������������������������15
Keys�����������������������������������������������������������������������������������������������������15
Conclusion������������������������������������������������������������������������������������������������15

Chapter 3: Sets�����������������������������������������������������������������������������������17
Accessing, Adding, and Removing an Element of a Set���������������������������17
Accessing an Element������������������������������������������������������������������������������17
Adding an Element�����������������������������������������������������������������������������������19
Removing Elements����������������������������������������������������������������������������������19
Set Operations������������������������������������������������������������������������������������������20
Comparison Operations�����������������������������������������������������������������������20
Membership and Equality Operations������������������������������������������������������24
Set Equality�����������������������������������������������������������������������������������������24
Set Membership����������������������������������������������������������������������������������24
Conclusion������������������������������������������������������������������������������������������������26
Chapter 4: Stacks�������������������������������������������������������������������������������27
Using Swift with Stacks���������������������������������������������������������������������������28
Stack Structures���������������������������������������������������������������������������������������31
Stack Extensions��������������������������������������������������������������������������������������32
Conclusion������������������������������������������������������������������������������������������������32
Chapter 5: Queue��������������������������������������������������������������������������������33
Implementation����������������������������������������������������������������������������������������35
Conclusion������������������������������������������������������������������������������������������������40

iv

www.allitebooks.com
Table of Contents

Chapter 6: Linked Lists�����������������������������������������������������������������������41


Implementation����������������������������������������������������������������������������������������42
Node����������������������������������������������������������������������������������������������������43
Singly Linked List�������������������������������������������������������������������������������������43
Adding New Values to a Linked List���������������������������������������������������������44
Append������������������������������������������������������������������������������������������������45
Insert���������������������������������������������������������������������������������������������������46
Removing New Values from a Linked List������������������������������������������������47
removeLast������������������������������������������������������������������������������������������48
remove(at:)������������������������������������������������������������������������������������������49
Doubly Linked List������������������������������������������������������������������������������������50
Append������������������������������������������������������������������������������������������������52
Remove Node Method�������������������������������������������������������������������������53
Remove(at:)�����������������������������������������������������������������������������������������53
Summary��������������������������������������������������������������������������������������������������54

Chapter 7: Hash Table�������������������������������������������������������������������������55


Creating Hash Table����������������������������������������������������������������������������������56
Retrieving Data from a Hash Table������������������������������������������������������57
Updating a Value in a Hash Table�������������������������������������������������������������58
Removing a Value from a Hash Table�������������������������������������������������������59
Summary��������������������������������������������������������������������������������������������������60

Chapter 8: Trees����������������������������������������������������������������������������������61
Creation����������������������������������������������������������������������������������������������������62
Insertion����������������������������������������������������������������������������������������������63
Searching Data������������������������������������������������������������������������������������64
Conclusion������������������������������������������������������������������������������������������������66

v
Table of Contents

Chapter 9: Trie Data Structure������������������������������������������������������������67


Why a Trie?�����������������������������������������������������������������������������������������������67
How It Works��������������������������������������������������������������������������������������������68
Implementation����������������������������������������������������������������������������������������69
Insert���������������������������������������������������������������������������������������������������70
Query���������������������������������������������������������������������������������������������������71
Remove�����������������������������������������������������������������������������������������������72
Conclusion������������������������������������������������������������������������������������������������75

Chapter 10: Binary Tree����������������������������������������������������������������������77


Binary Tree Primer������������������������������������������������������������������������������������77
Properties of Binary Tree���������������������������������������������������������������������78
Types of Binary Trees��������������������������������������������������������������������������78
Implementation����������������������������������������������������������������������������������������81
Tree Traversal (Also Known As Tree Search)���������������������������������������������81
In-Order Traversal��������������������������������������������������������������������������������82
Pre-Order Traversal�����������������������������������������������������������������������������83
Post-Order Traversal����������������������������������������������������������������������������85
Conclusion������������������������������������������������������������������������������������������������86

Chapter 11: Binary Search Tree����������������������������������������������������������87


Implementation����������������������������������������������������������������������������������������88
Insert��������������������������������������������������������������������������������������������������������89
Search������������������������������������������������������������������������������������������������������92
Example�����������������������������������������������������������������������������������������������94

vi
Table of Contents

Delete�������������������������������������������������������������������������������������������������������94
Deleting a Leaf������������������������������������������������������������������������������������94
Deleting a Node with One Child�����������������������������������������������������������95
Deleting a Node with Two Children�����������������������������������������������������96
Conclusion����������������������������������������������������������������������������������������������100

Chapter 12: Red–Black Tree�������������������������������������������������������������101


Implementation��������������������������������������������������������������������������������������102
Rotation���������������������������������������������������������������������������������������������105
Insertion��������������������������������������������������������������������������������������������109
Deletion���������������������������������������������������������������������������������������������115
Conclusion����������������������������������������������������������������������������������������������120

Chapter 13: Big O������������������������������������������������������������������������������121


Time Complexity�������������������������������������������������������������������������������������121
Space Complexity�����������������������������������������������������������������������������������124
Drop the Constants and Nondominant Terms�����������������������������������������125
How to Calculate Complexities?�������������������������������������������������������������126
Add vs. Multiply��������������������������������������������������������������������������������������128
Amortized Time��������������������������������������������������������������������������������������129
Log N Runtimes���������������������������������������������������������������������������������130
Recursive Runtimes��������������������������������������������������������������������������131
Conclusion����������������������������������������������������������������������������������������������132

Chapter 14: Sorting Algorithms��������������������������������������������������������133


Bubble Sort���������������������������������������������������������������������������������������������133
Implementation���������������������������������������������������������������������������������136

vii
Table of Contents

Selection Sort�����������������������������������������������������������������������������������������137
Implementation���������������������������������������������������������������������������������139
Insertion Sort������������������������������������������������������������������������������������������140
Implementation���������������������������������������������������������������������������������142
Merge Sort���������������������������������������������������������������������������������������������143
Implementation���������������������������������������������������������������������������������146
Quick Sort�����������������������������������������������������������������������������������������������148
Implementation���������������������������������������������������������������������������������151
Pivot Selection����������������������������������������������������������������������������������152
Conclusion����������������������������������������������������������������������������������������������153

Chapter 15: Search Algorithms��������������������������������������������������������155


Linear Search�����������������������������������������������������������������������������������������155
Implementation���������������������������������������������������������������������������������157
Binary Search�����������������������������������������������������������������������������������������158
Implementation���������������������������������������������������������������������������������160
Conclusion����������������������������������������������������������������������������������������������161

Chapter 16: Graph Algorithms����������������������������������������������������������163


Directed Graphs��������������������������������������������������������������������������������������164
Undirected Graphs����������������������������������������������������������������������������������164
Weighted Graphs������������������������������������������������������������������������������������165
Breadth-First Search (BFS)��������������������������������������������������������������������166
Implementation���������������������������������������������������������������������������������171
Depth-First Search (DFS)������������������������������������������������������������������������174
Implementation���������������������������������������������������������������������������������179

viii
Table of Contents

Dijkstra’s Algorithm��������������������������������������������������������������������������������182
Implementation���������������������������������������������������������������������������������190
Algorithm�������������������������������������������������������������������������������������������191
Conclusion����������������������������������������������������������������������������������������������194
Chapter 17: Choosing the Best Algorithm����������������������������������������195
Sorting Algorithms����������������������������������������������������������������������������������196
Bubble Sort���������������������������������������������������������������������������������������196
Selection Sort������������������������������������������������������������������������������������196
Insertion Sort�������������������������������������������������������������������������������������197
Merge Sort����������������������������������������������������������������������������������������197
Quick Sort������������������������������������������������������������������������������������������197
Search Algorithms����������������������������������������������������������������������������������198
Linear Search vs. Binary Search�������������������������������������������������������198
Graph Search Algorithms (GSA)��������������������������������������������������������������200
Dijkstra’s Algorithm��������������������������������������������������������������������������������201

Index�������������������������������������������������������������������������������������������������203

ix
About the Author
Elshad Karimov is an experienced programmer with more than 8 years
experience of different programming languages and a solid background in
iOS development as well as Oracle, SQL, C#, Java, Python and HTML/CSS.
He’s familiar with the performance limits and characteristics of Swift and
the nature and function of embedded databases and system datastores.

xi
About the Technical Reviewer
Felipe Laso is a Senior Systems Engineer working at Lextech Global
Services. He’s also an aspiring game designer/programmer. You can follow
him on Twitter @iFeliLM or on his blog.

xiii
CHAPTER 1

Arrays
In this chapter, you will learn about arrays, their built-in properties, and
how to retrieve, add, and remove elements from them.

I ntroduction
An array is simply a container that can hold multiple data (values) of
any data type in an ordered list; this means that you get the elements
in the same order as you defined the items in the array. Instead of
declaring individual variables, such as number0, number1, and so on
… until number99, you declare one array variable such as numbers and
use numbers[0], numbers[1], and numbers[99] to represent individual
variables.
The simplest type of array is the linear array, which is also known as
a one-dimensional array. In Swift, arrays are a zero-based index. A one-­
dimensional array can be written simply as shown in the following and
elements can be accessed using a[i], where i is an index between 0 and n:

é a0 ù
êa ú
a=ê ú
1

ê ú
ê ú
ë an û

© Elshad Karimov 2020 1


E. Karimov, Data Structures and Algorithms in Swift,
https://doi.org/10.1007/978-1-4842-5769-2_1
Chapter 1 Arrays

Another form of array is the multidimensional array which is a typical


matrix:

éa00 a01 a02 ù


a=ê
ë a10 a11 a12 úû

Main Features of Arrays


Each element can be accessed through its index, as shown in Figure 1-1.

c[0] c[1] c[2]


Blue Green Red

Figure 1-1. Element index

Arrays reserve a specific capacity of memory for holding their contents,


and when the capacity is full, the array allocates a larger region of memory
for additional elements and copies its elements into the new storage.
This is why adding elements to an array can be time consuming. The new
storage size grows exponentially as compared to the old size, so as the
array grows, reallocation occurs less and less often. The capacity property
determines the total amount of elements the array can contain before
exceeding and having to allocate new memory.
As shown in Figure 1-2, we’re appending “Black” to the array that’s just
about to exceed its capacity. The item doesn’t get added right away, but
what happens is new memory is created elsewhere, all items are copied
over, and finally the item is added to the array. This is called reallocation:
allocating new storage at another region in memory. The array’s size
increases exponentially. In Swift, this is called the geometric growth
pattern.

2
Chapter 1 Arrays

Black
c[0] c[1] c[2]
Blue Green Red

Capacity : 3

Reallocation

c[0] c[1] c[2] c[3]


Blue Green Red Black

Capacity : 6
Figure 1-2. Reallocation

As the elements are added to an array, the array will automatically


resize when it runs out of capacity. It is more efficient to allocate additional
reserve capacity at creation time if you know ahead of time an array will
contain a large number of elements.

var intArray = Array<Int>()

//Shows the array capacity


intArray.capacity
intArray.reserveCapacity(500)
intArray.capacity

3
Chapter 1 Arrays

When you make a copy of an array, a separate physical copy is not


made during the assignment. Swift implements a feature called copy on
write, which means that the array elements are not copied until a mutating
operation is performed.
You can create arrays with the following syntaxes:

//Create an array using full array syntax


var intArray = Array<Int>()

//Create an array using shorthand syntax


intArray = [Int]()

//Use array literal declaration


var intLiteralArray: [Int] = [1, 2, 3]

//Use shorthand literal declaration


intLiteralArray = [1, 2, 3]

// Create an array with a default value


intLiteralArray = [Int](repeating: 2, count: 5)

Retrieving Elements from an Array


There are multiple ways to retrieve values from an array. We can retrieve
using index or loop through using the for–in syntax.

var myIntArray = [1,2,3,4,5]


var aNumber = myIntArray[2]
print(aNumber)

//Output
3

4
Chapter 1 Arrays

We can iterate through the elements in an array.

for element in myIntArray {


    print(element)
}

//Output
1
2
3
4
5

Adding Elements to an Array


There are two ways of adding an element to an array. Append function can
be used to add an element at the end of the array and insert function can
be used to insert an element at a specific index in an existing array.

myIntArray.append(11)
print(myIntArray)

//Output
[1, 2, 3, 4, 5, 11]

myIntArray.insert(12, at: 3)
print(myIntArray)

//Output
[1, 2, 3, 12, 4, 5, 11]

5
Chapter 1 Arrays

Removing Elements from an Array


Similarly, there are four ways of removing elements from an array. By using
removeLast() function, an element at the end of an array can be removed,
removeFirst() to remove the first element, remove(at:) to remove an
element at a specific index, and removeAll() to remove all elements.

myIntArray.removeLast()
myIntArray.removeFirst()
myIntArray.remove(at: 1)
myIntArray.removeAll()

Built-in Functions and Properties


In the remaining sections, we’ll discuss some built-in functions and
properties of arrays.

isEmpty
This property determines if an array is empty or not. It returns true if an
array does not contain any value, otherwise returns false.

let myIntArray = [1, 3, 5, 6]


print(myIntArray.isEmpty)

When you run the program, the output will be

false

6
Chapter 1 Arrays

First and Last


These properties are used to access the first and last elements of an array.

print(myIntArray.first)
print(myIntArray.last)

When you run the program, the output will be

Optional(1)
Optional(6)

As you can see, the output of these properties is optional. This means
that if the array is empty the return will be nil.

Reversed and Reverse


Reversed function returns completely new collection with the elements of
an array in reverse order. Reverse function reverses the collection itself.

let reversedArray = Array(myIntArray.reversed())


print(reversedArray)

When you run the program, the output will be

[6, 5, 3, 1]

Count
This property returns the total number of elements in an array.

print(myIntArray.count)

When you run the program, the output will be

7
Chapter 1 Arrays

Important
While using subscript syntax to access elements of an array in Swift, you
must be sure the value lies in the index; otherwise, you will get a runtime
crash. Let’s see this in the following example:

print(myIntArray[-1])

When you run the program, the output will be

fatal error: Index out of range

In the preceding program, there is no value in the index -1. So when


you try to access the value in the index, you will get a runtime crash.
To prevent this, first find the index of the element you are trying to
remove. And then remove the element at the index as follows:

var myIntArray = [1, 3, 5, 7]


if let index = myIntArray.firstIndex(of: 5) {
    print("found index")
    let val =  myIntArray.remove(at: index)
    print(val)
}

When you run the program, the output will be

found index
5

Conclusion
In this chapter, you have learned about the general structure of an array,
how to declare it in Swift, and how to select, add, and remove elements.
In the following chapter, you will learn about the data structure type of
dictionaries.

8
CHAPTER 2

Dictionaries
In this chapter, the dictionary type of data structures will be discussed. You
will learn how to access, add, remove, and modify elements in a dictionary.
Moreover, built-in properties and functions of dictionaries will be covered.

I ntroduction
A dictionary is another data type collection in Swift. This data structure
takes its name from real-world dictionaries where you have words
and their associated meaning; in programming, we use dictionaries to
associate a key with its value, so any value can be identified as long as we
know the key. If we look inside a real dictionary, we will find words and
each word has accompanying explanation and meaning.
Miller : a person who owns or works in a corn mill
There is a similar concept in Swift, in which we can express the
preceding dictionary entry like this where a key is a word from a real
dictionary and the value is an accompanying explanation.

It is an unordered collection that holds multiple data as key/value pair.


Each value is associated with a unique key that acts as an identifier for the
value in the dictionary. A key is used to store and retrieve values from the
dictionary.
© Elshad Karimov 2020 9
E. Karimov, Data Structures and Algorithms in Swift,
https://doi.org/10.1007/978-1-4842-5769-2_2
Chapter 2 Dictionaries

var myDict = ["Miller" : "a person who owns or works in a corn mill",
"Programmer" : "a person who writes computer programs"]

We can add more than one key to the dictionary as long as it conforms
to the declaration of the dictionary. We can create dictionaries by explicitly
stating how the data is structured in a dictionary. In this, case we have the
key String data type and the value is also a String data type. If we state the
dictionary structure, the declaration will be like this:

var myDict : [String : String] = ["Miller" : "a person who owns


or works in a corn mill",
"Programmer" : "a person who
writes computer programs"]

Suppose you may want to search the capital city of a country. In that
case, you will create a dictionary with the key country and value capital
city. Now, you get the capital city from the collection by searching with
the key country. If we want to create a dictionary with different types of
values, we need to declare a heterogeneous dictionary which conforms to
the Hashable protocol. This type of dictionaries is useful when converting
JSON payloads.

var myDictionary = [AnyHashable: Any]()

There are three ways of dictionary declaration:

// 1St
var myDictionary = Dictionary<Int, String>()

// 2nd
var myDictionary = [Int: String]()

// 3rd
var myDictionary:[Int: String] = [:]

10
Chapter 2 Dictionaries

It is possible to create a dictionary from two arrays:

let countryKeys = ["US", "UK", "AZ"]


let countryValues = ["United States", "United Kingdom",
"Azerbaijan"]
let newDictionary = Dictionary(uniqueKeysWithValues:
zip(countryKeys,countryValues))
print(newDictionary)

When you run the program, the output will be

["AZ": "Azerbaijan", "US": "United States", "UK": "United


Kingdom"]

Accessing Values in a Dictionary


To access any value in a dictionary, you need to include the key of the
value you want to access within square brackets immediately after the
name of the dictionary. It is possible to use optional binding and forced
unwrapping or determine if the value exists to retrieve the pair. If you
are absolutely sure that the key exists, only then in this case forced
unwrapping can be used.
Using optional binding

//Using optional binding


var myDictionary : [Int: String] = [1: "One", 2: "Two", 3: "Three"]
if let optValue = myDictionary[4] {
    print(optValue)
} else {
    print("Key not found")
}

11
Chapter 2 Dictionaries

The output will be

Key not found

Using forced unwrapping

//Using forced unwrapping


let forcedValue = myDictionary[3]!
print(forcedValue)

The output will be

Three

It is possible to iterate through a dictionary and return the key pair,


which can be decomposed into named constants.

for (key, value) in myDictionary {


    print("The value for \(key) is \(value)")
}

The output will be key: 3

The value for 1 is One


The value for 2 is Two
The value for 3 is Three

It is possible to retrieve only the keys or values independently. As


mentioned before, dictionaries are unordered collections, so when you
iterate through them, there is no guarantee that it will be listed in an order.
But there might be occasions that you want an iteration in an ordered
manner, and for those cases, sort(_:) method can be used. This will
return an array containing sorted elements of a dictionary. In the following
code, $0.0 is the first key/value pair and $0.1 is the second key/value pair.
These pairs are compared and will be ordered based on this comparison.
Then, a map method is used to retrieve the data for the key or value.

12
Chapter 2 Dictionaries

let sortedArray = myDictionary.sorted(by: {$0.0 < $1.0})

for (key) in sortedArray.map({$0.0}) {


    print("The key: \(key)")
}

for (value) in sortedArray.map({$0.1}) {


    print("The value: \(value)")
}

The output will be

The key: 1
The key: 2
The key: 3
The value: One
The value: Three
The value: Four

Adding/Modifying to a Dictionary
To add a value to a dictionary, a subscript notation or
updateValue(_:forKey) method can be used. The subscript notation can
also be used to modify any existing value.

// Add a new element to the dictionary


myDictionary.updateValue("Four", forKey: 4)

//Add a new element using subscript notation


myDictionary[5] = "Five"

13
Chapter 2 Dictionaries

Removing a Value from a Dictionary


To remove a value from a dictionary, a subscript notation and
removeValue(forKey:) method can be used. This method returns the
value that was removed.

//Remove a value from a dictionary using the method


let removedValue = myDictionary.removeValue(forKey: 1)

//Remove a value using subscript notation


myDictionary[2] = nil

Built-in Functions and Properties


isEmpty
It returns true if a dictionary does not contain any value, otherwise returns
false.

print(myDictionary.isEmpty)

The output will be

false

First
This property is used to access the first element of a dictionary.

let myDictionary : [Int: String] = [1: "One", 2: "Two",


3: "Three"]

print(myDictionary.first)

14
Chapter 2 Dictionaries

The output will be

Optional((key: 2, value: "Two"))

Count
It returns the total number of elements in a dictionary.

print(myDictionary.count)

The output will be

Keys
It returns all the keys inside a dictionary.

let dictKeys  = Array(myDictionary.keys)


print(dictKeys)

The output will be

[1,2,3]

Conclusion
In this chapter, you have learned about the structure of dictionaries
and how to access, add, remove, and modify elements in it. The built-in
properties and functions provided by the Swift programming language are
also covered.

15
CHAPTER 3

Sets
It is an unordered collection (meaning you won't get the elements in the
same order as you defined) of unique, non-nil elements. It must conform
to the Hashable protocol. This means it has to provide a hashValue
property. This is important because sets are unordered and hashValue is
used to access the elements of the sets.
Access time is more efficient than arrays. When searching for an
element inside an array, the worst scenario is O(n), where n is the size of
the array, but in a set, it is always constant O(1). Unlike other collection
types while declaring sets, a set type must be specified.

//Full syntax declaration


var intSet = Set<Int>()

//Initialize a set from an array literal


var stringSet: Set = ["One", "Two", "Three"]

 ccessing, Adding, and Removing


A
an Element of a Set
Accessing an Element
As previously mentioned, sets are unordered and do not have indexes,
so it is not possible to access elements of a set using subscript syntax
as arrays. It can be accessed through using the set’s own methods and
properties or using for–in loops.
© Elshad Karimov 2020 17
E. Karimov, Data Structures and Algorithms in Swift,
https://doi.org/10.1007/978-1-4842-5769-2_3
Chapter 3 Sets

// Accessing an element
for num in stringSet {
    print(num)
}

The output will be

Two
One
Three

For ordered iteration, the following method can be used:

//Ordered iteration
for num in stringSet.sorted() {
    print(num)
}

To check if an element exists in a set, contains(_:) method can be


used.

// Check if the element exists


if stringSet.contains("One") {
    print("Element found")
} else {
    print("Element not found")
}

The output will be

Element found

18
Chapter 3 Sets

Adding an Element
Using the insert() method, a new element can be added to a set.

//Insert a new element


stringSet.insert("Four")
print(stringSet)

The output will be

["Four", "One", "Two", "Three"]

Removing Elements
There are several methods that can be used to remove the elements from
a set.

remove(_:) – To remove an element when you have


an instance of it

remove(at:) – To remove the element when you


know the index

removeFirst() – To remove the first element and


starting index

removeAll() or removeAll(keepCapacity) – To
remove all elements

//Remove an element
stringSet.remove("Four")

//Remove an element in an index


if let idx = stringSet.firstIndex(of: "One") {
    stringSet.remove(at: idx)
}

19
Discovering Diverse Content Through
Random Scribd Documents
“You go down to your tea and leave her ladyship’s looks alone. I
don’t know what you’re doing hanging about this landing at such an
hour of the day.”
Payne was an old servant in the Wynyard family, and he was aware
it had been generally said that “Master Owen had the looks and Miss
Leila the brains.” Master Owen was always a wild, harum-scarum
young fellow, and it wasn’t at all unlikely that he had got into one of
his scrapes. With this conviction implanted in his mind, Payne
deliberately descended the stairs, issued an edict to one of the
footmen, and retired into his lair and the evening paper.
CHAPTER II
BROTHER AND SISTER

“Well,” began Lady Kesters, as the door closed, “I suppose you


have seen him?”
“I have very much seen him,” replied her brother, who had thrown
himself into a chair; “I did a sprint across the park, because I know
your ladyship cannot bear to be kept waiting. Everything must be
done to the minute in this establishment.”
“Yes,” she agreed; “and you come from a country where time is no
object—everything is for ‘To-morrow.’ Now, tell me about Uncle
Richard. Was he furious?”
“No; I believe I would have got off better if he had been in a rage. He
received me in a ‘more in sorrow than in anger’ frame of mind, spoke
as deliberately as if he had written his speech, and learnt it by heart;
he meant every word he said.”
“I doubt it,” said his sister, who had been filling the teapot, and now
closed the lid with a decisive snap. “Let me hear all you can
remember.”
“He said he had done his best for me since I was a kid—his only
brother’s son and his heir,—that he had sent me to Eton——”
“As if you didn’t know that!” she interrupted.
“Engineered me into the Service——”
“Yes, yes, yes!” with a wave of her hand. “Tell me something new.”
“He says that he is sick of me and my failures—is that new?”
“What does he propose?” asked Lady Kesters.
“He proposes that, for a change, I should try and get along by
myself, and no longer hang on to other people.”
“Well, there is some sense in that.”
“He says that if I continue as I’ve begun, I’ll develop into the awful
loafer who haunts men’s clubs, trying to borrow half a sov. from old
pals, and worrying them with begging letters.”
“A pretty future for you, Owen!”
“He swears I must work for my living and earn my daily bread; and
that, if, for two years from now, I can maintain myself honourably in
this country or the Continent—Asia, Africa, and America are barred
—and neither get into debt, prison, or any matrimonial entanglement
——” he paused for a moment to laugh.
“Yes, yes,” said his sister impatiently; “and if you comply with all
these conditions?”
“He will reinstate me, put me into Wynyard to take the place of his
agent, and give me a handsome screw. But if I play the fool, he takes
his solemn oath he will leave everything he possesses to a hospital,
and all I shall come in for will be the bare estate, an empty house,
and an empty title—and that he hopes to keep me out of for the next
thirty years!”
“No doubt he will,” agreed his sister; “we are—bar accidents—a
long-lived stock.”
“He also said that he was only fifty-six; he might marry; a Lady
Wynyard——”
“No fear of that,” she interposed; “the old servants will never permit
it, and never receive her. But how are you to earn your living and
your daily bread?”
“That, he declares, is entirely my affair. Of course he doesn’t expect
much from a wooden-headed duffer like me; he knows I’ve no
brains, and no, what he calls ‘initiative or push.’ He doesn’t care a
rap if I sweep a crossing or a chimney, as long as I am able to
maintain myself, become independent, and learn to walk alone.”
“So that is Uncle Richard’s programme!” said Lady Kesters
reflectively. “Now, let’s have some tea,” and she proceeded to pour it
out. “The little cakes are cold and stodgy, but try these sandwiches.
Martin is away to-night—he had to go to a big meeting in Leeds, and
won’t be home. I shall send for your things. I suppose you are at
your old quarters in Ryder Street?”
“Yes; they have been awfully decent to me, and kept my belongings
when I was away.”
“And you must come here for a week, and we will think out some
scheme. I wish you could stay on and make your home here. But
you know Martin has the same sort of ideas as Uncle Richard; he
began, when he was eighteen, on a pound a week, and made his
own way, and thinks every young man should do the same.”
“I agree with him there—though it may sound funny to hear me say
so, Sis. I hope you don’t imagine I’ve come back to loaf; I shall be
only too glad to be on my own.”
“I suppose you have no money at all?” she inquired, as she
replenished his teacup.
“I have fifteen pounds, if you call that nothing, all my London kit, a
pair of guns, and a gold watch.”
“But what brought you back so suddenly? You did not half explain to
me this morning, when you tumbled from the skies.”
“Well, you see,” he began, as he rose and put down his cup, “the
Estancia I was on was of the wrong sort, as it happened, and a
rotten bad one. Uncle Richard was tremendously keen to deport me,
and he took hold of the first thing he heard of, some crazy advice
from a blithering old club fogey who did not know a blessed thing
about the country. The Valencia Estancia, a horse-breeding one, was
far away inland—not one of those nearer Buenos Ayres and
civilisation,—it belonged to a native. The proprietor, Vincino, was
paralysed from a bad fall, and the place was run by a ruffian called
Murcia. I did not mind roughing it; it’s a splendid climate, and I liked
the life itself well enough. I got my fill of riding, and a little shooting—
duck, and a sort of partridge—and I appreciated the freedom from
the tall hat and visiting card.”
“You never used many of those!” she interposed.
“No. From the first I never could stand Murcia; he was such an oily
scoundrel, and an awful liar; so mean and treacherous and cruel,
both to men and animals. He drank a lot of that frightfully strong spirit
that’s made out there—fermented cane—and sometimes he was
stark mad, knocking the servants and the peons about; and as to the
horses, he was a fiend to them. He killed lots of the poor brutes by
way of training; lassoed them—and broke their hearts. It made my
blood boil, and, as much as I could, I took over the breaking-in
business. When I used to jaw him and remonstrate, it made him wild,
and he always had his knife into me on the sly.”
“How?”
“The stiffest jobs, the longest days, the largest herds, were naturally
for the English ‘Gringo.’”
“What is that?”
“A dog. He never called it to my face—he was too much of the cur—
but we had several shakes up, and the last was final. One afternoon
I caught him half-killing a wretched woman that he said had been
stealing coffee. It was pay-day, all the employés, to a man and child,
were assembled in the patio—you know what that is? An enclosed
courtyard with the house round it. This was a grand old dilapidated
Spanish Estancia, with a fine entrance of great iron gates. It was a
warm, still sort of afternoon. As I cantered across the campo I heard
harrowing shrieks, and, when I rode in, I soon saw what was up!
Murcia, crazy with drink, was holding a wretched creature by her hair
and belabouring her with a cattle-whip, whilst the crowd looked on,
and no one stirred a finger.”
“You did?” leaning forward eagerly.
“Rather! I shouted to him to hold hard, and he only cursed; so I
jumped off the horse and went for him straight. He dropped his victim
and tried to lay on to me with the whip; but the boot was on the other
leg, and I let him have it, I can tell you. It was not a matter of fists,
but flogging. My blood was up, and I scourged that blackguard with
all my soul and all my strength. He ran round and round the patio
yelling, whilst the crowd grinned and approved. I settled some of
Murcia’s scores on the spot and paid for many blows and outrages!
In the end he collapsed in the dust, grovelling at my feet, blubbering
and groaning, ‘a worm and no man.’ I think that’s in the Bible. Yes, I
gave that hulking, drunken brute a thrashing that he will never forget
—and those who saw it won’t forget it either. Naturally, after such a
performance I had to clear. You may do a lot of things out there; you
may even shoot a man, but you must never lay hands on an
overseer; so I made tracks at once, without pay, bonus, character, or
anything except the adoration of the employés, my clothes, and a
few pounds. Murcia would have run me in, only he would have
shown up badly about the woman. Well, I came down country in a
cattle-train, and found I was just short of coin to pay my way home.”
Leila stared into the fire in silence; her warm imagination transported
her to the scene her brother had described. She, too, was on the
campo, and heard the cries of the woman; she saw the Englishman
gallop through the gates, saw the cowardly crowd, the maddened
ruffian, the victim, and the punishment!
“But what did you do with your salary?” she asked, after an
expressively long pause; “surely you had no way of spending it?”
“That’s true. As I was to have a bonus, you know, on the year, my
salary was small, and I got rid of it easily enough.”
“Cards!” she supplemented; “oh, of course. My dear Owen, I’m afraid
you are hopeless!”
“Yes, I suppose it’s hereditary! After the day’s work there was
nothing to do. All the other chaps gambled, and I could not stand
with my hands in my pockets looking on; so I learnt the good old
native game of ‘Truco,’ but I had no luck—and lost my dollars.”
“And after your arrival at Buenos Ayres in the cattle-train, what
happened?”
“Well, naturally, I had no spare cash to spend in that little Paris: the
Calle Florida, and the Café Florian, and Palermo Park, saw nothing
of me, much less the magnificent Jockey Club. I searched about for
a cast home! I was determined to get back to the Old Country, for I
knew I’d do no good out there—I mean in Buenos Ayres; so I went
down to the Digue, where the big liners lie, and cadged for a job. I
believe they are pretty sick of chaps asking for a lift home, and I had
some difficulty in getting a berth; but, after waiting several days, I got
hold of a captain to listen to me. I offered to stoke.”
“Owen!”
“Yes; but he said, ‘You look like a stoker, don’t you? Why, you’re a
gentleman! You couldn’t stand the engine-room for an hour.
However, as I see you are not proud and they are short of hands in
the stewards’ pantry, they might take you on to wash plates.’”
Lady Kesters made no remark; her expression was sufficiently
eloquent.
“‘All right,’ I agreed, ‘I’ll do my little best.’ So I was made over to the
head steward. We carried a full number of passengers that trip, and,
when one of the saloon waiters fell sick, I was promoted into his
place, as I was clean and civil. Needless to say, I was thankful to get
away from the horrors of greasy plates and the fag of cleaning
knives. I can wait pretty well, the ladies liked me—yes, and I liked
them—and when we docked at Southampton yesterday, Owen, as
they called me, received nearly six pounds in tips, not to speak of a
steamer chair and a white umbrella!”
As he concluded, he walked over to the fire and stood with his back
to it. His sister surveyed him reflectively; she was thinking how
impossible it was to realise that her well-bred, smart-looking brother,
in his admirably cut clothes, and air of easy self-possession, had,
within twenty-four hours, been a steward at the beck and call of the
passengers on a liner. However, all she said was—
“So at any rate you have made a start, and begun to earn money
already.”
“Oh, that’s nothing new. I was never quite broke;” and, diving into his
pocket, he produced a little parcel, which he tossed into her lap.
“For me?”
“For who else?”
He watched her attentively as she untied the narrow bit of red and
yellow ribbon, unfolded a flat box, and discovered a beautiful plaque
or clasp in old Spanish paste. The design was exquisite, and the
ornament flashed like a coruscation of Brazilian diamonds.
“Oh, Owen, how perfect!” she gasped; “but how dare you? It must
have cost a fortune—as much as your passage money,” and she
looked up at him interrogatively.
“Never mind; it was a bargain. I picked it up in a queer, poky little
shop, and it’s real old, old Spanish—time of Ferdinand and Isabella
they said—and I felt I’d like to take something home to you; it will
look jolly well on black, eh?”
“Do you know it’s just the sort of thing that I have been aching to
possess,” she said, now holding it against her gown. “If you had
searched for a year you couldn’t have given me anything I liked so
much—so beautiful in itself, so rare and ancient, and so uncommon
that not one of my dear friends can copy it. Oh, it’s a treasure”—
standing up to look at her reflection as she held the jewel against her
bodice—“but all the same, it was wicked of you to buy it!”
“There are only the two of us, Sis, and why shouldn’t I give myself
that pleasure?”
“What a pretty speech!” and she patted his arm approvingly.
At this moment Payne entered, salver in hand.
“A telegram for you, my lady.”
“Oh,” picking it up, and tearing it open, “it’s from Martin. He is
detained till Saturday—three whole days;” then, turning to the butler,
she said, “You can take away the tea-table.”
As soon as the tea-things were removed, and Payne and his satellite
had departed, Lady Kesters produced a gold case, selected a
cigarette, settled herself comfortably in a corner of the sofa, and said

“Now, Owen, light up, and let us have a pow-wow! Have you any
plan in your head?”
“No,” he answered, “I’m afraid my head is, as usual, pretty empty,
and of course this ultimatum of Uncle Richard’s has been a bit of a
facer; I was in hopes he’d give me another chance.”
“What sort of chance?”
“Something in South Africa.”
“Something in South Africa has been the will-o’-the-wisp that has
ruined lots of young men,” she said; “you would do no good there, O.
You haven’t enough push, originality, or cheek; I believe you would
find yourself a tram conductor in Cape Town.”
“Then what about India? I might get a billet on some tea estate—yes
—and some shooting as well!”
“Tea-planters’ assistants, as far as I can gather, don’t have much
time for shooting. There is the tea-picking to look after, and the
coolies to overseer in all weathers. I believe the work in the rains is
awful and the pay is poor—you’d be much more likely to get fever
than shooting. Have you any other scheme?”
She glanced at her brother, who was lying back in an arm-chair, his
hands clasped behind his head, his eyes fixed on the fire. Yes, Owen
was undeniably good to look at, with his clean-shaven, clear-cut
face, well-knit figure, and length of limb. He shook his head, but after
a moment said—
“Now let us have your ideas, Sis. You are always a sure draw!”
“What about matrimony?” she asked composedly, and without
raising her eyes.
He turned and surveyed her with a stare of ironical amusement.
“On the principle that what is not enough for one will support two—
eh?”
“How can you be so silly! I don’t mean love in a cottage; I’m thinking
of an heiress. There are several, so to speak, on the market, and I
believe I could marry you off remarkably well, if you were not too
critical; there is Miss Goldberger—a really good sort—enormously
rich, an orphan, and hideous to the verge of fascination. She is in the
racing set—and——”
“No, thank you, Sis,” he broke in; “I’d rather drive a ’bus or motor any
day than live on my wife’s fortune. If I married one of your rich
friends I should hate it, and I guarantee that she’d soon hate me;
anyway, I’m not keen on getting married. So, as the young men in
shops say, ‘and the next article, please?’”
“Of course I know I need not again waste my breath talking to you of
business. Martin got you a capital opening in Mincing Lane, and you
threw it up; he’d taken a lot of trouble, and he is rather sore about it
still. He fancies you look down on the City.”
“I? He never made a greater mistake! The City would soon look
down on me. I’m no good at figures; I’ve no business ability or smart
alacrity. If I had not taken myself off, I’d soon have been chucked
out; besides, I never could stick in an office all day from ten to six. I’d
much rather wash plates! I want something that will keep me in the
open air all the time, rain or shine; and if I had to do with horses, so
much the better. How about a place as groom—a breaker-in of
young hunters?”
“Not to be thought of!” she answered curtly.
“No?” then drawing out another cigarette, “do you know, I’ve half a
mind to enlist. You see, I know something of soldiering—and I like it.
I’d soon get my stripes, and for choice I’d pick the ‘Death and Glory
Boys.’”
“Yes; you may like soldiering as an officer, with a fair allowance, a
couple of hunters, and polo ponies; but I’m not sure that Trooper
Wynyard would care for stables, besides his drill and work, and I
may be wrong, but I think you have a couple of troop horses to do
up.”
“Oh, I could manage all right! I’m rather handy with horses, though I
must confess the bronchos I’ve been riding lately did not get much
grooming.”
“No, no, Owen, I’m dead against enlisting, remember that,” she said
authoritatively. “I shall go and interview Uncle Richard to-morrow
morning, and have a tooth-and-nail combat on your behalf, find out if
he means to stick to his intention, or if I can’t persuade him to give
you a job on the estate, say as assistant agent, that would suit you?”
“You’re awfully clever, Sis,” said the young man, now rising and
leaning against the chimneypiece, “and in every respect the head of
the family. It’s downright wonderful how successfully you manage
other people’s affairs, and give one a push here and a hand there. I
am aware that you have immense and far-reaching—er—influence.
You have been the making of Kesters.”
His sister dismissed the statement with an impatient jerk of her
cigarette.
“Oh yes, you have,” he went on doggedly. “He was formerly a
common or garden wealthy man, whose daytime was divided
between meals and business; now he’s a K.C.B., sits on all sorts of
boards, has a fine place in the country, shoots a bit, is a Deputy-
Lieutenant, and I don’t know what all—and you’ve done it! But there
is one person you cannot manage or move, and that is Uncle
Richard; he is like a stone figure that all the wind and sun and rain
may beat on, and he never turns a hair.”
“How you do mix your metaphors!” she exclaimed; “who ever saw a
stone image with hair upon it! Well,” rising to stand beside him, “I
shall see what I can do in the morning. Now, let us put the whole
thing out of our heads and have a jolly evening. Shall we go to a
theatre? I suppose you’ve not been inside one since you were last in
town?”
“Oh yes, I was at theatres in Buenos Ayres, the Theatre Doria, a sort
of music hall, where I saw some ripping dancing.”
“I’ll telephone for stalls at something. You may as well have all the
fun you can before you start off to plough your lonely furrow.”
“It’s awfully good of you, Sis. I’m a frightful nuisance to the family—
something between a bad penny and a black sheep!”
“No, Owen, you know perfectly well you are neither,” she protested,
as she lit another cigarette. “You mentioned just now there are only
the two of us, and it would be rather strange if we did not stick by
one another. And there is this to be said, that although you’ve been
wild and extravagant, and your gambling and practical joking were
shocking, all the time you remain a gentleman; and there are two
things in your favour—you don’t drink——”
“No, thank God!” he responded, with emphasis.
“As far as I know you have never been mixed up with women—eh,
Owen?” and she looked at him steadily.
“No. To tell you the truth, I give them a wide berth. I’ve seen some
pretty awful affairs they had a hand in. To be candid, I’m a little shy
of your sex.”
“That is funny, Owen,” she replied, “considering it was on account of
a woman you have just been thrown out of a job.”
“You could hardly expect a man to stand by and see a brute like
Murcia knocking a poor creature about—half-killing her—and never
interfere!”
“No, of course; but you must not make the mistake of being too
chivalrous—chivalry is costly—and it is my opinion that it has cost
you a good deal already. That detestable de Montfort was not the
first who let you in, or persuaded you to pull his chestnuts out of the
fire. Come now, own up—confess to the others.”
“No—no”—and he smiled—he had a charming smile—“there is such
a thing as honour among thieves.”
“That’s all very noble and generous, my dear brother, but some of
the thieves were not honourable.”
Her dear brother made no reply; he was staring fixedly into the fire
and thinking of Hugo de Montfort. How little had he imagined, when
he backed Hugo’s bill, that the scribbling of his signature would
make such an awful change in his own life!
Hugo and he had been at Eton in the same house; they had fagged
together, sat side by side in chapel, and frequently shared the same
scrapes. Later they had lost sight of one another, as Owen had
struggled into the Service and gone out to India. Some years later,
when stationed at the depôt, he and de Montfort had come across
one another once more.
Hugo de Montfort was a self-possessed young man, with sleek black
hair and a pair of curiously unreadable grey eyes: an idler about
town—clever, crafty, unscrupulous, and much given to cards and
racing.
He welcomed his old pal Wynyard with enthusiasm—and secretly
marked him for his own. Wynyard—so said report—was a nailing
rider, a good sort, popular, and known to be the nephew and heir of a
rich, unmarried uncle; so he played the rôle of old schoolfellow and
best pal for all it was worth.
The plausible, insidious scoundrel, who lived by his wits, was on his
last legs—though he kept the fact a secret—was seen everywhere,
carried a bold front, and owned a magnificent 60 h.p. motor, which
was useful in more ways than one. He was staying at the Métropôle
at Folkestone, and, struck by a bright idea—so he declared—
motored over to Canterbury one fine Sunday morning, and carried
off his friend to lunch.
As they sat smoking and discussing recent race meetings, weights,
and jockeys, de Montfort suddenly put down his cigar and said—
“I say, look here, Owen, old man. I’m in rather a tight fix this week. I
want two thousand to square a bookie—and, like the real sporting
chap you are—will you back my name on a bill?”
Owen’s expression became unusually grave; backing a bill was an
iniquity hitherto unknown to him. Uncle Dick had recently paid up
handsomely, and he had given certain promises; and, indeed, had
curtailed his expenses, sold two of his ponies, and had made up his
mind to keep strictly within his allowance.
“Of course it’s a mere form,” pursued de Montfort, in his swaggering,
off-hand way, “I swear to you. Do you think I’d ask you, if it was not
safe as a church! I’ll have the coin in a fortnight; but just at the
moment I’m terribly short, and you know yourself what racing debts
mean. So I come to you, my old pal, before any one; you are such a
rare, good, generous, open-handed sort! Don’t for a moment
suppose that you will be responsible,” declared this liar; “I’ll take up
the bill when it falls due; I’d as soon let in my own mother as a pal
like you.”
In short, Hugo was so urgent and so plausible, that his victim was
persuaded and carried away by eloquence and old memories,
accompanied de Montfort to a writing-table, where he signed O. St.
J. Wynyard—and repented himself before his signature had been
blotted!
Two days later Owen received a beautiful silver cigarette-case,
inscribed, as a token of friendship from de Montfort, and this was
succeeded by an alarming silence. When the time approached for
the bill to fall due, Wynyard wrote anxious epistles to his old
schoolfellow—who appeared to be one of the crowd who believe that
letters answer themselves! Then he went up to town and sought him
at his rooms and club; no one could give him any tidings of Hugo
beyond the fact that he was abroad—a wide and unsatisfactory
address. He sent distracted telegrams to some of the runaway’s
former haunts; there was no reply. The fatal day arrived, and Owen
was compelled to interview his uncle and make a clean breast of the
whole business; and his uncle was furious to the verge of apoplexy.
“They used to say,” he shouted, “put the fool of the family into the
army; but my fool shall not remain in the Service! I’ll pay up the two
thousand you’ve been robbed of for the sake of my name—and out
you go! Send in your papers to-day!”

Lady Kesters was contemplating her face in the overmantle, which


also reflected her brother’s unusually grave visage.
“Owen,” she said, “what a pity it is that I hadn’t your looks and you
my brains.”
They presented a contrast, as they examined one another in the
glass. The woman’s dark, irregular face, her keen, concentrated
expression; the man with clear-cut features, sleepy, deep-set grey
eyes, and close-cropped light brown hair.
“I think you are all right as you are, Sis,” he remarked, after a
reflective pause.
“But you are not,” she snapped. “Now, if you had my head. Oh, how I
long to be a man! I’d have gone into Parliament. I’d have helped to
manage the affairs of a nation instead of the affairs of a family. I’d
have worked and slaved and made myself a name—yes, and gone
far!”
“What’s the good of going far?” he asked, in a lazy voice.
“Ah,” she exclaimed, with a touch of passion, “you have no ambition;
you don’t even know what the word means! Look at the men in the
Commons, who have worked themselves up from nothing to be
powers in the land, whose influence is far-reaching, whose voices
are heard at the ends of the earth. What would be your ambition,
come now?” and she surveyed him with sparkling eyes.
“Certainly not to go into Parliament,” he answered, “and sit in the
worst atmosphere in London for eight months of the year.”
“Well, at least it’s an electrical atmosphere, charged with vitality! And
your ambition?” she persisted.
“To win the Grand National, riding my own horse, since you must
know.”
“Pooh!” she exclaimed, snapping her fingers with a gesture of scorn,
“and what a paltry aim!—the yells of a raving mob, a ‘para’ in the
papers, and the chance of breaking your neck.”
“Better than breaking something else! I’m told that a political career,
with its incessant work, crushing disappointments, worry, and fag,
has broken many a fellow’s heart.”
“Heart! Nonsense; I don’t believe you have one. Well, now, as we
are dining early, you had better see about your things from Ryder
Street, and I will go and ’phone for stalls for The Giddy Girl.”
CHAPTER III
THE LAST WORD GOES BEGGING

Sir Richard Wynyard, aged fifty-six, was a little, grey, square-


shouldered man, with a good heart and bad temper. His father, the
notorious Sir Fulke, had put his two sons into the army, given them
small and irregularly paid allowances, and then abandoned them to
their own devices, whilst he squandered the family patrimony on
horses and cards. When Richard, his heir, was quartered in Dublin,
he fell desperately in love with a beautiful Irish girl; but, painfully
aware of his own empty purse, he was too prudent to marry—unlike
his reckless younger brother, who adventured a runaway match on a
captain’s pay and debts. Major Wynyard made no sign, much as this
silence cost him, and when, after his father’s death, he had at last a
roof to offer—Wynyard, a stately old place, although somewhat
dismantled—he sought his lady-love in haste, but, alas! he was
months too late; she had already been summoned to another home,
—the beautiful Rose O’Hara, his heart’s desire, was dead.
This was said to have been Sir Richard’s sole love-affair, and the
one grief of his life. The late baronet’s reckless extravagance had
shattered the fortunes of his descendants; his heir found himself
compelled to let the land, close the Hall, sell off the horses, and take
up his abode with his mother in the town house in Queen’s Gate;
where he lived and how, was indifferent to him, he seemed to have
no heart for anything. This was attributed to his supreme disgust at
inheriting such a legacy of debt; but the real truth was that the loss of
the beautiful Rose had temporarily stunned her lover.
Lady Wynyard, once a celebrated beauty, was now a weak and
withered old dowager, tyrannically ruled by her servants. When she,
too, was carried to the ancestral vault, her son still remained in the
gloomy family abode, and, more from apathy than anything else, fell
under the thrall of her retainers.
Between his father’s and his mother’s debts, Sir Richard found
himself sorely pressed, and he took Martin Kesters, his schoolfellow
and friend, into his confidence.
“I shall be a crippled man all my life,” he declared; “it will take years
to nurse the property into anything like what it was in my
grandfather’s day; and, by that time, that young chap, Owen, will
step into my shoes.”
“Well, Dick, if you don’t mind a bit of risk,” said his companion, “I
know a thing that will set you on your legs and make your fortune;
but it’s not absolutely certain. Still, if it comes off, you get five
hundred per cent. for your money, and become a semi-millionaire.
It’s an Australian gold-mine, and I believe it’s going to boom!”
“Anything is better than this half-and-half existence,” said Sir Richard
impatiently. “You have a long head, Martin, and I’ll take your tip and
put on all I can scrape. I’ll mortgage some outlying land, sell some of
the good pictures and the library, and be either a man or a mouse.
For once in my life I’ll do a big gamble. If I win, you say it’s a big
thing; if I lose, it means a few hundreds a year and a bedroom near
my club for the rest of my days. I take no middle course—I’ll be a
rich man or a pauper.”
And Sir Richard was as good as his word; he scraped up fifteen
thousand pounds, staked the whole sum on his venture—and won.
Subsequently, he cleared the property, invested in some securities,
began to feel at ease in the world, and travelled widely. Having
known the pinch and humiliation of genteel poverty and practised
stern self-denial in his youth, Sir Richard was naturally the last man
to have any sympathy with a nephew—a restless, reckless scatter-
brain—who was following in the footsteps of his squandering
forefathers. The good-looking young scapegrace must have a sharp
lesson, and learn the value of money and independence.
Lady Kesters’ promised interview with her uncle took place. He was
fond of Leila in his own brusque fashion, and secretly plumed himself
on having manœuvred her marriage.
“Well, Leila, I suppose you have come about this precious brother of
yours?” he began, as she was ushered into the smoking-room.
“Of course I have, Uncle Dick,” she replied, as she imprinted a kiss
upon his cheek and swept into a chair. “Something must be done!”
and she looked at him with speculative eagerness.
“There I agree with you,” he answered. “And Owen is the man to do
it. God helps those who help themselves!”
“Owen is most anxious to make another start; but it is not easy for a
soldier man, brought up as he has been.”
“Brought up as a rich man’s heir,” broke in her uncle, with a quick,
impatient movement; “more fool the rich man! I gave the fellow a
good education, good allowance, good send-off. I got him into his
father’s old regiment, and made him a decent allowance; he did fairly
well in India, I admit; but as soon as he came home to the depôt, he
seemed to have lost his head. Why, I believe the young scamp
actually kept racers, and as for his hunters, I never saw finer cattle in
my life! One day, when I happened to run down to Canterbury to visit
him, I noticed a servant exercising a couple of horses—such a pair! I
was bound to stop and admire them, and the groom informed me
that they belonged to Lieutenant Wynyard of the Red Hussars; and
Mr. Wynyard’s uncle hadn’t as much as a donkey to his name!”
“But could have thousands if he chose,” interposed Leila. “As for
racing, it was only his hunters Owen put into regimental
steeplechases and that sort of thing.”
“And that sort of thing came devilish expensive!” snapped Sir
Richard, who was now pacing the room. “I had to pay his debts. I
paid them twice, and he promised on his word of honour to turn over
a new leaf. The next thing he did was to back a bill for an infernal
young swindler, and let me in for two thousand pounds—that was the
last straw!”
“Yes, I know it was,” assented his niece; “but really, Uncle Dick,
Owen was not so much to blame as you believe. He was very steady
out in India for four years; coming home, as you say, went to his
head; he did not realise that money does not go nearly as far here—
especially in an expensive cavalry regiment. He kept polo ponies
and racing ponies in Lucknow, and could not understand that he
could not do the same at home. As to the bill, he is not suspicious, or
sharp at reading character, and is staunch to old friends—or those
he mistakes for friends—as in the case of young de Montfort. He had
never heard what a ‘wrong un’ he turned out; they were at Eton——”
“Yes, I know—same house—same puppy-hole!” growled her uncle.
“And when Mr. de Montfort looked up Owen and told him a pathetic
and plausible tale about his affairs, and swore on his word of honour
that his signature was a mere formality—and——”
“Cleared off to Spain and left me to pay!” interposed Sir Richard,
coming to a halt.
“Owen had to pay too,” retorted his sister, with a touch of bitterness.
“You mean that I made him leave the Service? Yes, I could not afford
to go on supporting an extravagant young ass.”
“Owen is not brilliant, Uncle Dick, but he is no fool.”
“A fool and another man’s money are soon parted. Life was made
too easy for the chap—very different to what I found it at his age. I
had no hunters, no dozens of silk shirts, and rows of polo boots; I
never was to be met lounging down Piccadilly as if the whole earth
belonged to me.”
“Well, at least, Uncle Dick, you were never compelled to give up a
profession you adored, when you were barely five-and-twenty.”
“I’ve given up a lot,” he answered forcibly, “and when I was older
than him; but never mind me; we are talking of Owen. After leaving
the Hussars, Kesters took him on, and got him a capital billet in the
City—a nice soft berth, ten to four, but my gentleman could not stand
an office stool and tall hat, and in five months he had chucked——”
Leila nodded. It was impossible to deny this indictment.
“So then it was my turn again; and I thought a little touch of real work
would be good for the future Sir Owen Wynyard, and, after some
trouble, I heard of a likely opening in the Argentine on the Valencia
Estancia, well out of the way of towns and temptation—a horse-
breeding ranch, too. You see I studied the fellow’s tastes, eh?” And
Sir Richard twirled his eyeglasses by the string—a trick of his when
he considered that he had scored a point.
“I gave him his passage and outfit, and put a few hundreds into the
concern as a spec. and to insure him an interest, and within twelve
months here he is back again on my hands—the proverbial rolling
stone!” He cleared his throat, and continued: “Now, Leila, my girl,
you have a head on your shoulders, and you know that these rolling
stones find their way to the bottom, and I am going to block my
specimen in good time. I suppose he told you what I said to him
yesterday?”
“Yes; he came straight to Mount Street from seeing you.”
“He has got to shift for himself for two years, to earn his bread, with
or without butter, to guarantee that he does not take a penny he has
not worked for, that he does not get into debt or any matrimonial
engagement; should he marry a chorus-girl, by Jove I’ll burn down
Wynyard! If, by the end of that time, he turns up a steady,
industrious, independent member of society, I will make him my
agent—he shall have an adequate allowance, the house to live in,
and most of my money when I am dead!”
Lady Kesters was about to speak, but with a hasty gesture her uncle
interposed.
“I may as well add that I think myself safe in offering this prize, for it’s
my belief that Owen will never win it. He has the family fever in his
veins—the rage for gambling—and he is like the patriarch Reuben,
‘unstable as water and cannot excel.’ At the end of six months he will
be penniless, and you and Kesters will have to come to his rescue;
for my part I wash my hands of him.”
“Uncle Dick,” she said, rising, “I think you are too hard on Owen; he
would not have come back from South America if he had not had a
row with the manager of the Estancia: surely you could not expect an
English gentleman—an Englishman—to stand by and see a poor
woman nearly beaten to death?”

You might also like