100% found this document useful (4 votes)
34 views

Mastering Swift 3 Linux 1st Edition Hoffman 2024 scribd download

Hoffman

Uploaded by

zabellsengu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
34 views

Mastering Swift 3 Linux 1st Edition Hoffman 2024 scribd download

Hoffman

Uploaded by

zabellsengu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Download Full ebookname - Read Now at ebookname.

com

Mastering Swift 3 Linux 1st Edition Hoffman

https://ebookname.com/product/mastering-swift-3-linux-1st-
edition-hoffman/

OR CLICK BUTTON

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Essentials of the Theory of Fiction 3 revised Edition


Michael J. Hoffman

https://ebookname.com/product/essentials-of-the-theory-of-
fiction-3-revised-edition-michael-j-hoffman/

ebookname.com

Beginning iPhone Development with Swift 3 Exploring the


iOS SDK 3rd ed. Edition Maskrey

https://ebookname.com/product/beginning-iphone-development-with-
swift-3-exploring-the-ios-sdk-3rd-ed-edition-maskrey/

ebookname.com

Learning Swift 1st Edition Wagner

https://ebookname.com/product/learning-swift-1st-edition-wagner/

ebookname.com

Combustion of Pulverised Coal in a Mixture of Oxygen and


Recycled Flue Gas 1st Edition Dobrin Toporov (Auth.)

https://ebookname.com/product/combustion-of-pulverised-coal-in-a-
mixture-of-oxygen-and-recycled-flue-gas-1st-edition-dobrin-toporov-
auth/
ebookname.com
Mormonism For Beginners 1st Edition Stephen Carter

https://ebookname.com/product/mormonism-for-beginners-1st-edition-
stephen-carter/

ebookname.com

Pricing Online Marketing Behavior and Analytics 1st


Edition Giampaolo Viglia (Auth.)

https://ebookname.com/product/pricing-online-marketing-behavior-and-
analytics-1st-edition-giampaolo-viglia-auth/

ebookname.com

Medical Nutrition Disease A Case Based Approach 3rd


Edition Lisa Hark

https://ebookname.com/product/medical-nutrition-disease-a-case-based-
approach-3rd-edition-lisa-hark/

ebookname.com

Interventions Following Mass Violence and Disasters


Elspeth Cameron Ritchie

https://ebookname.com/product/interventions-following-mass-violence-
and-disasters-elspeth-cameron-ritchie/

ebookname.com

The Languages of Business 1st Edition Francesca Bargiela-


Chiappini

https://ebookname.com/product/the-languages-of-business-1st-edition-
francesca-bargiela-chiappini/

ebookname.com
Computer Science Notable Research and Discoveries
Frontiers of Science 1st Edition Kyle Kirkland

https://ebookname.com/product/computer-science-notable-research-and-
discoveries-frontiers-of-science-1st-edition-kyle-kirkland/

ebookname.com
Mastering Swift 3 - Linux

Learn to build fast and robust applications on the Linux


platform with Swift

Jon Hoffman

BIRMINGHAM - MUMBAI
Mastering Swift 3 - Linux
Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be caused
directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: January 2017

Production reference: 1281216

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78646-141-4
www.packtpub.com
Credits

Author Copy Editor

Jon Hoffman Safis Editing

Reviewers Project Coordinator

Andrea Prearo Shweta H Birwatkar


Doug Sparling

Commissioning Editor Proofreader

Ashwin Nair Safis Editing

Acquisition Editor Indexer

Smeet Thakkar Aishwarya Gangawane

Content Development Editor Graphics

Sumeet Sawant Disha Haria

Technical Editor Production Coordinator

Egan Lobo Nilesh Mohite


About the Author
Jon Hoffman has over 20 years of experience in the field of information technology. Over
these 20 years, Jon has worked in the areas of system administration, network
administration, network security, application development, and architecture. Currently, Jon
works as a senior software engineer for Syn-Tech Systems.

Jon has developed extensively for the iOS platform since 2008. This includes several apps
that he has published in the App Store, apps that he has written for third parties, and
numerous enterprise applications. What really drives Jon is the challenges that the field of
information technology provides and there is nothing more exhilarating to him than
overcoming a challenge.

You can follow Jon on his blogs: http://masteringswift.blogspot.com and http://myro


boticadventure.blogspot.com.

Some of Jon’s other interests are watching baseball (Go Sox) and basketball (Go Celtics). Jon
also really enjoys Tae Kwon Do where he and his oldest daughter Kailey earned their black
belts together early in 2014, Kim (his wife) earned her black belt in December 2014, and his
youngest daughter is currently working towards her black belt.

I would like to thank my wonderful wife, Kim, without whose support, encouragement,
patience, and understanding, this book would have never been written. I would also like to
thank my two wonderful daughters, Kailey and Kara, who have both been my inspiration
and driving force since the days they were born.
About the Reviewers
Andrea Prearo is a software engineer with over 15 years of experience.

He is originally from Italy, and after a decade of writing software in C/C++ and C#, he
moved to the Bay Area in 2011 to start developing mobile apps.

In the last few years, he has been focusing on Swift, Objective-C, iOS, and microservices,
with some short explorations of the Android platform.

Currently, he is a member of the iOS development team at Capital One, working on the
company’s flagship mobile banking app.

His interests include reading books, watching movies, and hiking. From time to time, he
also blogs about tech on Medium: https://medium.com/@andrea.prearo.

I would like to thank my wonderful wife, Nicole, for her never-ending support in all my
endeavors.

Doug Sparling works as a technical architect and software developer for Andrews McMeel
Universal, a publishing and syndication company in Kansas City, MO. At AMU, he uses Go
for web services, Python for backend services, and Ruby on Rails and WordPress for
website development, and Objective-C, Swift, and Java for native iOS and Android
development. AMU’s sites include www.gocomics.com, www.uexpress.com,
www.puzzlesociety.com, and dilbert.com.

He also was the co-author of a Perl book, Instant Perl Modules for McGraw-Hill and a
reviewer for other Packt Publishing books, including Swift Data Structure and Algorithms,
jQuery 2.0 Animation Techniques: Beginner’s Guide, and WordPress Web Application
Development. Doug has also played various roles for Manning Publications as a reviewer,
technical development editor, and proofer, working on books such as Go in Action, The
Well-Grounded Rubyist 2nd Edition, iOS Development with Swift, and Programming for
Musicians and Digital Artists.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters and receive exclusive discounts and offers on Packt books and
eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt
books and video courses, as well as industry-leading tools to help you plan your personal
development and advance your career.

Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Table of Contents
Preface 1
Chapter 1: Taking the First Steps with Swift 7
What is Swift? 7
Swift's features 9
Installing Swift 3 for Linux 10
Swift language syntax 12
Comments 12
Semicolons 15
Parentheses 15
Curly brackets 16
Assignment operators do not return a value 16
Spaces are optional in conditional and assignment statements 17
Hello World 17
Executing Swift code 19
Swift and the Swift REPL 20
Swift compiler 21
Using the Swift Package Manger 22
Editors for Swift 24
Summary 24
Chapter 2: Learning About Variables, Constants, Strings, and Operators 25
Constants and variables 26
Defining constants and variables 26
Type safety 27
Type inference 28
Explicit types 29
Numeric types 30
Integers 30
Floating point 33
The Boolean type 34
The String type 35
Optional variables 37
Enumerations 42
Operators 46
The assignment operator 46
Comparison operators 46
Arithmetic operators 47
The remainder operator 47
Compound assignment operators 48
The ternary conditional operator 48
The logical NOT operator 49
The logical AND operator 49
The logical OR operator 49
Summary 50
Chapter 3: Using Swift Collections and the Tuple Type 51
Swift collection types 52
Mutability 52
Arrays 53
Creating and initializing arrays 53
Accessing the array elements 55
Counting the elements of an array 56
Is the array empty? 57
Appending to an array 57
Inserting a value into an array 57
Replacing elements in an array 58
Removing elements from an array 58
Adding two arrays 59
Reversing an array 59
Retrieving a subarray from an array 59
Making bulk changes to an array 60
Algorithms for arrays 60
Sort 61
Sorted 62
Filter 62
Map 63
forEach 63
Iterating over an array 64
Dictionaries 65
Creating and initializing dictionaries 65
Accessing dictionary values 66
Counting key or values in a dictionary 66
Is the dictionary empty? 67
Updating the value of a key 67
Adding a key-value pair 68
Removing a key-value pair 68

[ ii ]
Set 69
Initializing a set 69
Inserting items into a set 70
The number of items in a set 70
Checking whether a set contains an item 70
Iterating over a set 70
Removing items in a set 71
Set operations 71
Tuples 73
Summary 74
Chapter 4: Control Flow and Functions 75
What we have learned so far 75
Curly brackets 76
Parentheses 76
Control flow 77
Conditional statements 77
The if statement 77
Conditional code execution with the if…else statement 78
The for loop 79
Using the for…in loop 79
The while loop 81
Using the while loop 81
Using the repeat…while loop 82
The switch statement 83
Using case and where statements with conditional statements 87
Filtering with the where statement 87
Filtering with the for…case statement 88
Using the if…case statement 90
Control transfer statements 91
The continue statement 91
The break statement 92
The fallthrough statement 93
The guard statement 93
Functions 95
Using a single-parameter function 95
Using a multi-parameter function 97
Defining a parameter's default values 97
Returning multiple values from a function 99
Returning optional values 100
Adding external parameter names 101
Using variadic parameters 102

[ iii ]
Inout parameters 103
Nesting functions 104
Putting it all together 105
Summary 106
Chapter 5: Classes and Structures 107
What are classes and structures? 107
Similarities between classes and structures 108
Differences between classes and structures 108
Value versus reference types 108
Creating a class or structure 110
Properties 110
Stored properties 111
Computed properties 113
Property observers 116
Methods 117
Custom initializers 119
Internal and external parameter names 121
Failable initializers 122
Inheritance 125
Overriding methods and properties 128
Overriding methods 128
Overriding properties 131
Preventing overrides 131
Protocols 132
Protocol syntax 132
Property requirements 132
Method requirements 134
Extensions 136
Memory management 137
How ARC works 138
Strong reference cycles 140
Summary 144
Chapter 6: Using Protocols and Protocol Extensions 145
Protocols as types 146
Polymorphism with protocols 148
Type casting with protocols 149
Protocol extensions 151
Summary 159

[ iv ]
Chapter 7: Protocol-Oriented Design 160
Requirements 160
Object-oriented design 161
Protocol-oriented design 166
Protocol inheritance 167
Protocol composition 168
Animal – protocol-oriented design 169
Using the where statement with protocols 171
Summary 172
Chapter 8: Writing Safer Code with Error Handling 173
Error handling prior to Swift 2.0 174
Native error handling 175
Representing errors 175
Throwing errors 176
Catching errors 178
Summary 183
Chapter 9: Custom Subscripting 184
Introducing subscripts 184
Subscripts with Swift arrays 185
Read and write custom subscripts 186
Read-only custom subscripts 187
Calculated subscripts 188
Subscript values 188
External names for subscripts 189
Multidimensional subscripts 189
When not to use a custom subscript 192
Summary 193
Chapter 10: Using Optional Types 194
Introducing optionals 194
The need for optional types in Swift 196
Defining an optional 197
Using optionals 198
Forced unwrapping optionals 198
Optional binding 198
Returning optionals from functions, methods, and subscripts 200
Using optionals as a parameter in a function or method 201
Optional types with tuples 202
Optional chaining 202

[v]
The nil coalescing operator 204
Summary 205
Chapter 11: Working with Generics 206
An introduction to generics 206
Generic functions 207
Generic types 211
Associated types 215
Summary 218
Chapter 12: Working with Closures 219
An introduction to closures 219
Simple closures 220
Shorthand syntax for closures 223
Using closures with Swift's array algorithms 226
Changing functionality 230
Selecting a closure based on results 233
Creating strong reference cycles with closures 235
Summary 239
Chapter 13: Using C Libraries with Swift 240
Modules 241
Creating a custom module 242
Creating the Cpcap module 243
Using the Cpcap module 244
Linux man pages 249
Summary 251
Chapter 14: Concurrency and Parallelism in Swift 252
Concurrency and parallelism 253
GCD 254
Helper functions 255
Creating queues 256
Creating and using a concurrent queue 257
Creating and using a serial queue 259
async versus sync 260
Executing code on the main queue function 261
Using asyncAfter 261
Summary 262
Chapter 15: Swifts Core Libraries 263
Apple's URL loading system 264
URLSession 265

[ vi ]
URLSessionConfiguration 265
URLSessionTask 266
URL 266
URLRequest 266
HTTPURLResponse 266
REST web services 267
Making an HTTP GET request 267
Making an HTTP POST request 270
Formatter 272
DateFormatter 273
NumberFormatter 275
FileManager 276
Summary 278
Chapter 16: Swift on Single Board Computers 279
The BeagleBone Black 280
BeagleBone Black's expansion headers 283
Installing Swift 285
SwiftyBones3 285
Sources directory 286
SwiftyBuild 287
Blinking an LED with the SBDigitalGPIO type 287
TMP36 temperature sensor with the SBAnalog type 290
Autonomous robot 294
Summary 309
Chapter 17: Swift Formatting and Style Guide 310
What is a programming style guide? 310
Your style guide 311
Do not use semicolons at the end of statements 312
Do not use parentheses for conditional statements 312
Naming 312
Custom types 312
Functions and methods 313
Constants and variables 313
Indenting 314
Comments 314
Using the self keyword 315
Constants and variables 315
Optional types 316
Use optional binding 316

[ vii ]
Use optional chaining over optional binding for multiple unwrapping 317
Use type inference 317
Use shorthand declaration for collections 317
Use switch rather than multiple if statements 318
Don't leave commented-out code in your application 318
Summary 319
Chapter 18: Adopting Design Patterns in Swift 320
What are design patterns? 320
Creational patterns 322
The singleton design pattern 323
Understanding the problem 324
Understanding the solution 324
Implementing the singleton pattern 325
The builder design pattern 327
Understanding the problem 327
Understanding the solution 327
Implementing the builder pattern 327
Structural design patterns 333
The bridge pattern 333
Understanding the problem 333
Understanding the solution 334
Implementing the bridge pattern 334
The façade pattern 338
Understanding the problem 338
Understanding the solution 338
Implementing the façade pattern 339
The proxy design pattern 341
Understanding the problem 341
Understanding the solution 341
Implementing the proxy pattern 342
Behavioral design patterns 344
The command design pattern 345
Understanding the problem 345
Understanding the solution 345
Implementing the command pattern 346
The strategy pattern 348
Understanding the problem 348
Understanding the solution 349
Implementing the strategy pattern 349
Summary 351
Index 352

[ viii ]
Preface
In December 2015, Apple released Swift as an open source project on its GitHub page. With
this release, Apple also released a version of Swift for Linux. Swift is a general-purpose
programming language that takes a modern approach to development.

What this book covers


Chapter 1, Taking the First Steps with Swift, gives a brief introduction to the Swift language.
We will also cover the basic Swift language syntax and discuss proper language styles.

Chapter 2, Learning About Variables, Constants, Strings, and Operators, shows how to use
variables and constants in Swift. We will also look at the various data types and how to use
operators in Swift.

Chapter 3, Using Swift Collections and the Tuple Type, looks at how we can use the Swift
collection types to store related data. These collection types are the dictionary, array and set
types.

Chapter 4, Control Flow and Functions, covers control flow and functions in Swift. It is
essential to understand the concepts in this chapter before going on. Every application that
we write, beyond the simple Hello World applications, will rely very heavily on the control
flow statements and functions.

Chapter 5, Classes and Structures, dedicates itself to Swift's classes and structures. We'll look
at what makes them similar and what makes them different. We'll also look at access
controls and object-oriented design. We'll close this chapter out by looking at memory
management in Swift.

Chapter 6, Using Protocols and Protocol Extensions, covers both protocols and protocol
extensions in detail since protocols are very important to the Swift language. Having a solid
understanding of them will help us write flexible and reusable code.

Chapter 7, Protocol-Oriented Design, covers the best practices of protocol-oriented Design


with Swift. It will be a brief overview of what is covered in my Swift 3 Protocol-Oriented
Programming book.

Chapter 8, Writing Safer Code with Error Handling, looks at Swift's error-handling features.
This feature is really important for writing safe code. While we are not required to use this
feature in our custom types however it does give us a uniform manner to handle and
Preface

respond to the error. Apple has also started to use this error handling in their frameworks.
It is recommended that we use error handling in our code.

Chapter 9, Custom Subscripting, discusses how we can use custom subscripts in our classes,
structures, and enumerations. Subscripts in Swift can be used to access elements in a
collection. We can also define custom subscripts for our classes, structures, and
enumerations.

Chapter 10, Using Optional Types, explains what optional types really are, what the various
ways to unwrap them are, and optional chaining. For a developer who is just learning Swift,
optional types can be one of the most confusing items to learn.

Chapter 11, Working with Generics, explains how Swift implements generics. Generics allow
us to write very flexible and reusable code that avoids duplication.

Chapter 12, Working with Closures, teaches us how to define and use closures in our code.
Closures in Swift are similar to blocks in Objective-C except that they have a much cleaner
and easier to use syntax. We will conclude this chapter with a section on how to avoid
strong reference cycles with closures.

Chapter 13, Using C Libraries with Swift, explains how we can link and use standard C
libraries with our Swift applications. This gives Swift developers access to all of the same
libraries that Linux C developers have access to.

Chapter 14, Concurrency and Parallelism in Swift, shows how to use Grand Central Dispatch
(GCD) to add concurrency and parallelism to our applications. Understanding and
knowing how to add concurrency and parallelism to our apps can significantly enhance the
user experience.

Chapter 15, Swift's Core Libraries, explains how to use the Swift core libraries, including
reading/writing files, network primitives, and JSON parsing.

Chapter 16, Swift on Single Board Computers, shows how we can use Swift to develop IoT
devices and robots using a single board computer.

Chapter 17, Swift Formatting and Style Guide, defines a style guide for the Swift language
that can be used as a template for enterprise developers who need to create a style guide,
since most enterprises have style guides for the various languages that they develop in.

Chapter 18, Adopting Design Patterns in Swift, shows you how to implement some of the
more common design patterns in Swift. A design pattern identifies a common software
development problem and provides a strategy for dealing with it.

[2]
Preface

What you need for this book


To follow along with the samples in this book, the reader will need a computer that has
Ubuntu 14.04, 15.10, 16.04, or 16.10 installed. To follow along with the samples in Chapter
16, Swift on Single Board Computers, the reader will need a BeagleBone Black or Green single
board computer and the additional components mentioned in the chapter.

Who this book is for


Swift is a modern, fast, and safe open source language created by Apple. This book is for
Linux developers who are interested in learning how to use Swift to quickly create exciting
applications for the desktop, server, and embedded Linux platforms. This book will be
written for developers who learn best by working with code, as every topic discussed will
be reinforced with code samples.

Conventions
In this book, you will find a number of text styles that distinguish between different kinds
of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can
change the value of the highTemperture variable without an error because it is a variable"

A block of code is set as follows:


var x = 3.14 // Double type
var y = "Hello" // String type
var z = true // Boolean type

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
<head>
<script src="d3.js" charset="utf-8"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>

Any command-line input or output is written as follows:


sudo mkdir swift

[3]
Preface

New terms and important words are shown in bold. Words that you see on the screen, for
example, in menus or dialog boxes, appear in the text like this: "In order to download new
modules, we will go to Files | Settings | Project Name | Project Interpreter."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book-what you liked or disliked. Reader feedback is important for us as it helps us develop
titles that you will really get the most out of. To send us general feedback, simply e-
mail feedback@packtpub.com, and mention the book's title in the subject of your
message. If there is a topic that you have expertise in and you are interested in either
writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.

Downloading the example code


You can download the example code files for this book from your account at http://www.p
acktpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.c
om/supportand register to have the files e-mailed directly to you.

You can download the code files by following these steps:

1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.

[4]
Preface

5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:

WinRAR / 7-Zip for Windows


Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPubl
ishing/Mastering-Swift-3-Linux. We also have other code bundles from our rich catalog
of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book


We also provide you with a PDF file that has color images of the screenshots/diagrams used
in this book. The color images will help you better understand the changes in the output.
You can download this file from https://www.packtpub.com/sites/default/files/down
loads/MasteringSwift3Linux_ColorImages.pdf.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-
we would be grateful if you could report this to us. By doing so, you can save other readers
from frustration and help us improve subsequent versions of this book. If you find any
errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting
your book, clicking on the Errata Submission Form link, and entering the details of your
errata. Once your errata are verified, your submission will be accepted and the errata will
be uploaded to our website or added to any list of existing errata under the Errata section of
that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/conten


t/supportand enter the name of the book in the search field. The required information will
appear under the Errata section.

[5]
Preface

Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come
across any illegal copies of our works in any form on the Internet, please provide us with
the location address or website name immediately so that we can pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected pirated


material.

We appreciate your help in protecting our authors and our ability to bring you valuable
content.

Questions
If you have a problem with any aspect of this book, you can contact us
at questions@packtpub.com, and we will do our best to address the problem.

[6]
Taking the First Steps with Swift
1
Ever since I was 12 years old and wrote my first program in the BASIC language,
programming has been a passion for me. Even as programming became my career, it
always remained more of a passion than a job, but over the past few years, that passion has
waned. I was unsure why I was losing that passion. I attempted to recapture it with some of
my side projects, but nothing really brought back the excitement that I used to have. Then,
something wonderful happened! Apple announced Swift, which is an exciting and
progressive language that has brought a lot of that passion back and made programming
fun for me again. Now that Apple has released Swift for Linux, I can use it for most of my
projects.

In this chapter, you will learn the following topics:

What is Swift?
Some of the features of Swift
How to get started with Swift
What are the basic syntaxes of the Swift language?

What is Swift?
Swift is Apple's new programming language that was introduced at the Worldwide
Developers Conference (WWDC) in 2014, alongside the integrated development
environment Xcode 6 and iOS 8. Swift was arguably the most significant announcement at
WWDC 2014, and very few people, including Apple insiders, were aware of the project's
existence prior to it being announced. In this initial release of Swift it could only be used to
develop applications for the Apple platforms.
Taking the First Steps with Swift

It was amazing, even by Apple's standards, that they were able to keep Swift a secret for as
long as they did, and no one suspected that they were going to announce a new
development language. At WWDC 2015, Apple made another big splash when they
announced Xcode 7 and Swift 2. Swift 2 was a major enhancement to the language. During
that conference, Chris Lattner said that a lot of enhancements were based directly on
feedback that Apple received from the development community. It was also announced at
WWDC 2015 that Apple would be releasing Swift as open source, and they would be
offering a port for Linux.

In December 2015, Apple officially released Swift as an open source project with the
swift.org site dedicated to the open source Swift community. The Swift repository is
located on Apple's github page (http://github.com/apple). The Swift evolution
repository (https://github.com/apple/swift-evolution) tracks the evolution of the
Swift language by documenting all of the proposed changes. You can also find a list of
proposals that were accepted and rejected in this repository. If you are interested in
understanding where Swift is heading, then you should check out this repository. It is
interesting to note that Swift 3 contains several enhancements that were proposed by the
community.

Swift 3 is a major enhancement to the language and is NOT source-compatible with


previous releases. It contains fundamental changes to the language itself and to the Swift
standard library. One of the main goals of Swift 3 is to be source-compatible across all
platforms, so the code that we write for one platform will be compatible with all other
platforms that Swift supports. This means that the code we develop for Mac OS will also
work on Linux.

Development on Swift was started in 2010 by Chris Lattner. He implemented much of the
basic language structure with only a few people being aware of its existence. It wasn't until
late 2011 that other developers began to really contribute to Swift, and in July 2013, it
became a major focus of the Apple Developer Tools group.

There are a lot of similarities between Swift and Objective-C. Swift adopts the readability of
Objective-C's named parameters and its dynamic object model. When we refer to Swift as
having a dynamic object model, we are referring to its ability to change at runtime. This
includes adding new (custom) types and changing/extending the existing types.

[8]
Taking the First Steps with Swift

While there are a lot of similarities between Swift and Objective-C, there are also significant
differences between them as well. Swift's syntax and formatting are a lot closer to Python
than Objective-C, but Apple did keep the curly braces. I know that Python people would
disagree with me, and that is all right because we all have different opinions, but I like the
curly braces. Swift actually makes the curly braces required for control statements such as
if and while, which eliminates bugs, such as the goto fail in Apple's SSL library, which
Apple patched in 2014.

Swift's features
When Apple said that Swift is Objective-C without the C, they were really only telling us
half the story. Objective-C is a superset of C and provides object-oriented capabilities and a
dynamic runtime to the C language. This means that, with Objective-C, Apple needed to
maintain compatibility with C, which limited the enhancements it could make to the
Objective-C language. As an example, Apple could not change how the switch statement
functioned and still maintains the C compatibility.

Since Swift does not need to maintain the same C compatibility as Objective-C, Apple was
free to add any feature/enhancement to the language. This allowed Apple to include the
best features from many of today's most popular and modern languages, such as Objective-
C, Python, Java, Ruby, C#, and Haskell.

The following chart shows a list of some of the most exciting enhancements that Swift
includes:

Swift feature Description


Type inference Swift can automatically deduce the type of the variable or constant,
based on the initial value.
Generics Generics allow us to write the code only once to perform identical
tasks for different types of objects.
Collection mutability Swift does not have separate objects for mutable or nonmutable
containers. Instead, you define mutability by defining the container
as a constant or variable.
Closure syntax Closures are self-contained blocks of functionality that can be
passed around and used in our code.
Optionals Optionals define a variable that might not have a value.
Switch statement The Switch statement has been drastically improved. This is one of
my favorite improvements.

[9]
Taking the First Steps with Swift

Multiple return types Functions can have multiple return types using tuples.
Operator overloading Classes can provide their own implementation of existing
operators.
Enumerations with In Swift, we can do a lot more than just defining a group of related
Associated values values with enumerations.
Before we can look at the Swift language itself, we need to download and install it. Let's
look at how we can install Swift.

Installing Swift 3 for Linux


The following instructions were current when this book was written and works for both
Ubuntu 15.10 and Ubuntu 16.04 LTS. The most up-to-date installation instructions can be
found on the swift.org installation page: https://swift.org/getting-started/#instal
ling-swift.

The first step in installing Swift is to install clang and configure it. The following are the
commands:
sudo apt-get update
sudo apt-get install clang-3.6
sudo update-alternatives -install /usr/bin/clang clang
/usr/bin/clang-3.6 100
sudo update-alternatives -install /usr/bin/clang++ clang++
/usr/bin/clang++-3.6 100

If you forget to do the update-alternatives commands, you will receive an error:


invalid inferred toolchain error when you try to build a package. Forgetting to run
the update-alternatives commands is a very common error.

Now that we have the correct clang installed, we need to download Swift. You can
download the latest version from the swift.org download page. The link for this page is: h
ttps://swift.org/download/.

[ 10 ]
Other documents randomly have
different content
alkondukis ŝin al li, pri la anima malsano, kiu de tiel longe bruligis
ŝian bruston, ruinigante ĉiujn plej bonajn homajn sentojn, kiu okupis
ŝian kapon, plenigante ĝin per ĉiam pli densa sufoka fumo de
mallumaj venenaj pensoj, pri tio li ne sciis. Li ne sciis, kaj tial li diris:
vi estas juna kaj sana, vi povas labori! Per tiuj vortoj li eldiris ion tute
pravan, kaj tamen samtempe li senscie faris kruelan maljustaĵon.

Antaŭ kelke da monatoj, eĉ antaŭ kelke da semajnoj Marta eble


komprenus ĉion, kio estis prava kaj vera en la al ŝi direktitaj vortoj
de la viro. Sed tiam, se ŝi stariĝus antaŭ li, ŝi petus laboron, nenion
alian krom laboro; nun ŝi petegis almozon, nun en la eldiritaj vortoj
ŝi aŭdis nenion krom moka maljustaĵo.

La flama ruĝo, kiun ŝi havis sur la vizaĝo kaj sur la frunto, kiam ŝi
etendis la manon, malaperis sen postesigno. Meze de la morta
paleco, kiu kovris ŝian vizaĝon, ŝiaj pupiloj, nigraj kaj profundaj kiel
abismo, brulis kiel vulkanoj. Kaj efektive vulkano eksplodis en ŝia
brusto, kiu forte leviĝadis kaj malleviĝadis, vulkano de kolero, envio
kaj... avideco.

De kolero, envio kaj avideco? Ĉu ĝi povas esti, ke Marta, tiu infano


de trankvila, ĉarma kampara domo, tiu iam estimata edzino, feliĉa
patrino, tiu virta estaĵo, kiu eĉ pro savo de sia vivo ne volis plenumi
laboron, por kiu ŝi ne sentis sin kapabla, tiu energia laborulino, kiu
kun ŝvito sur la vizaĝo kaj kun doloro en la koro sur ĉiuj vojoj de la
tero serĉadis honestan pecon da pano, tiu fiera animo, kiu iam
etendis la manojn al Dio kun la petego, ke li gardu ŝin kontraŭ sorto
de almozulo, — fariĝis viktimo de tiuj kruelaj, inferaj sentoj,
kondukantaj al malbonaj deziroj kaj agoj?

Kaj tamen tiel povis esti: ho ve! ho ve! ne sole povis, sed eĉ devis, ĝi
devis tiel fariĝi kaŭze de la neŝanĝebla, eterne logika kaj en sia
logikeco al nenio cedanta homa naturo. Ŝi ne estis senkorpa anĝelo,
ŝi ne estis supertera idealo, kiun ne tuŝas kaj ne renversas la blovoj
de la teraj ventegoj, ĉar tia idealo ne ekzistas sur la tero. Ŝi estis
homo, kaj se en la homa naturo ekzistas altaj pintoj, sur kiuj
disvolviĝas prudento, virtoj, sinoferemeco, heroeco, ekzistas ankaŭ
abismaj fundoj kun silente kaj kaŝite embuskantaj rampaĵoj de
minacaj tentoj kaj mallumaj instinktoj. Nenian homan estaĵon oni
devas tiel morte turmenti, tiel terure skui, ke en ĝi povu ekmoviĝi tiu
mistera fundo kun la tie silente embuskantaj ĝermoj de krimoj. En la
homa naturo ekzistas grandegaj potencoj, sed ekzistas ankaŭ
senlima senpoveco. Al ĉiu homa estaĵo oni devas doni kvanton da
rajtoj kaj rimedoj precize proporcian al la kvanto da devoj kaj
respondeco, kiuj pezas sur tiu estaĵo, ĉar alie ĝi ne plenumos kaj ne
eltenos tion, kion plenumi kaj elteni ĝi ne povos.

La venena maldolĉeco, kiu de tiel longe guto post guto kolektiĝadis


en la brusto de Marta, leviĝis en ŝi nun per grandega ondo, kaj kune
kun ĝi elnaĝis la rampaĵoj de tentoj kaj la serpentoj de pasioj, kiuj
antaŭe dormis profunde, poste iom post iom vekiĝis kaj nun estis
tute vekitaj kaj furioze ĵetiĝadis.

La juna sinjoro en la riĉa pelto elektadis tapiŝojn, arĝentajn korbojn,


porcelanajn vazojn kaj marmorajn statuetojn. Li aĉetis multe, li
pensis kredeble pri aranĝo de bela hejmo, en kiun li eble intencis
enkonduki junan edzinon.

Li kaj la mastro de la magazeno estis eble absorbitaj de sia komuna


okupo kaj forgesis pri la virino, kiu en ŝtona senmoveco kaj tomba
silento staris ĉe la muro. Ŝi ne forturnis la okulojn for de la mano de
la aĉetanto, kiu tenis grandan dikan monpaperujon plenan de mono.
Kial li havas tiom multe kaj mi havas nenion? ŝi pensis. Per kia rajto
li rifuzis al mi almozon? al mi, kies infano agonias en malvarmo kaj
sen savo, li, kiu tenas en la mano tiel grandan riĉecon? Li mensogis,
kiam li diris, ke mi estas juna kaj sana! mi estas pli ol maljuna, ĉar
mi transvivis min mem. Ĉu mi scias, kien forperdiĝis la antaŭa
Marta? Mi estas terure malsana, ĉar mi estas senforta kiel infano....
Kial do la homoj postulas, ke mi vivu per mia propra forto, se ili ne
donis ĝin al mi? kial ili ne donis al mi forton, se ili nun ĝin postulas
de mi? Li estas unu el miaj maljustagintoj, unu el miaj ŝuldantoj! li
devas doni!
La pensoj de tiu virino estis treege, senprudente malpravaj, kaj
tamen samtempe kaj koncerne ŝin mem kiel neeviteblaj, kiel
kompreneblaj ili estis! Ili estis bazitaj sur tiuj samaj maljustaĵoj, tiuj
samaj sortoj, tiu sama senforteco unuflanke kaj respondeco kaj
bezonoj duaflanke, kiuj naskis ĉiujn terurajn doktrinojn, kiuj de
tempo al tempo eksplodas en la mondo per bruligado kaj mortigado,
ĉiujn furiozajn pasiojn, kiuj, naskiĝinte pro manko de justeco, mem
perdas la senton de justeco, naskiĝinte de malbonagoj, mem faras
malbonagojn.

— Sekve, — diris la aĉetanta sinjoro, — kvardek kvin spesmilojn por


la tapiŝo, sepdek-kvin por la korboj, tridek por la porcelana vazo
kaj....

Li elprenis monon, por pagi al la komercisto la ŝuldatan sumon,


subite li haltis.

— Ha! — li diris, — mi preskaŭ povis forgesi! Vi intencis doni al mi ĉi


tiun bronzan grupon kaj tiun jen....

La komercisto alsaltis ridetante kaj serveme.

— Ĉu ĉi tiun? — li demandis.

— Ne, tiun, Niobon kun la infanoj...

— Niobon? ŝajnas al mi, ke vi deziris Kupidonon kun Venero?

— Povas esti; mi devas bone rigardi ilin ankoraŭ unu fojon.

Per nezorgeca mano, kiu videble kutimis disĵetadi grandajn sumojn,


li ĵetis la malfermitan monpaperujon sur la marmoran plataĵon de la
subspegula tableto, kaj li iris post la komercisto en la profundon de
la magazeno, kie sur palisandraj bretoj, sub vitraj kloŝoj, staris
mitologiaj bronzaj kaj marmoraj grupaj statuetoj.
La monpaperujo nezorgece ĵetita malfermiĝis pli larĝe, sur la
marmoran plataĵon elfalis el ĝi kelke da monpaperoj de diversa
valoro.

Tiujn monpaperojn rigardis la flamantaj okuloj de la virino, kiu staris


ĉe la muro. Kiel kelkaj specoj de serpentoj per sia rigardo magie
alforĝas la birdojn, tiel tiuj diverskoloraj paperetoj magie alforĝis al si
la nigrajn profundajn pupilojn de la virino.

Kiaj pensoj moviĝadis en la kapo de la virino, kiam ŝi tiamaniere


rigardis la fremdan riĉecon? estus malfacile esplori ilin ĉiujn, estus
ankoraŭ pli malfacile ŝpini el ili ian ordan fadenon. Tio ne estis
pensoj, tio estis ĥaoso; febra varmego de la korpo ĝin naskis,
malkvieteco de la spirito ĝin fortigis. Post du sekundoj da tia
rigardado Marta komencis tremi per la tuta korpo, ŝi mallevadis la
palpebrojn kaj tuj ilin relevadis, eltiradis la manon el la faldoj de la
tuko kaj tuj ĝin denove kaŝadis! videble ŝi batalis ankoraŭ kun si
mem, sed ho ve! ne ekzistis por ŝi espero de venko! Ne ekzistis tia
espero, ĉar ŝi ne havis jam sufiĉe da forto, ke ŝi povu kontraŭstari al
malhonora tento; ŝi ne havis jam sufiĉe da konscia pensado, ke ŝi
povu kompreni la malhonorecon de la tento; ŝi ne havis jam
konsciencon, kiu dronis en la maro da maldolĉo, kiu kolektiĝis en ŝia
brusto; ŝi ne havis jam honton, kiun forpelis la malestimo, kiun ŝi
sentis kontraŭ si mem, la longa vico da suferitaj humiliĝoj kaj la tiom
multe da fojoj akceptita almozo.... Ne ekzistis por ŝi fine espero de
venko, ĉar ŝi estis senkonscia, ĉar ŝian korpon bruligis varmego
naskiĝinta de malsato, malvarmo, sendormeco, sed ankaŭ de
malespero, kaj ŝian spiriton kaptis mallumaj furioj, elkoviĝintaj sur la
fundo de ŝia ribeliĝinta interno.

Subite la virino faris rapidan geston per la mano; unu el la paperetoj


malaperis de la marmora plataĵo, kaj samtempe la vitra pordo
malfermiĝis kaj tuj denove fermiĝis kun laŭta krako.

Aŭdinte tiun fortan kaj neatenditan krakon, la du personoj, kiuj en la


profundo de la magazeno estis okupitaj de elektado de mitologiaj
grupoj, returnis la vizaĝojn.

— Kio tio estis? — demandis la aĉetanta sinjoro.

La komercisto kuris al la mezo de la magazeno.

— Estas tiu virino, kiu tiel subite elkuris! — li ekkriis, — certe ŝi ion
ŝtelis.

La juna sinjoro ankaŭ alproksimiĝis al la pordo.

— Efektive, — li diris kun rideto, rigardante la marmoran plataĵon, —


ŝi forŝtelis al mi trispesmilan papereton. Nur unu tian mi havis, kaj
nun ĝi tie ne estas...

— Ha! kanajla almozulino! — ekkriis la komercisto. — Kiel? en mia


magazeno oni ŝtelas? ĝuste antaŭ miaj okuloj; ha, la senhonta!

Li alkuris al la pordo kaj malfermis ĝin larĝe.

— Policisto! — li ekkriis laŭte, starante sur la sojlo, — policisto!

— Kion vi deziras? — aŭdiĝis voĉo el la strato.

Flava lado ekbrilis sur la brusto de homo, kiu aperis sur la trotuaro
sub la strio da lumo fluanta el la magazeno.

— Tien, — diris la komercisto, malfacile spirante de kolero kaj


montrante per la fingro la straton, — tien kuris virino, kiu antaŭ
minuto ŝtelis en mia magazeno tri spesmilojn!

— Kaj en kiun flankon ŝi kuris?

— En tiun, — diris ia pasanto, kiu aŭdis la vortojn de la komercisto,


haltis antaŭ la magazeno kaj montris en direkto al la strato Nowy
Swiat. — Mi ŝin renkontis, ŝi estis vestita nigre, ŝi kuris kiel rabia,
nenion vidante antaŭ si, mi pensis, ke ŝi estas freneza!
— Oni devas ŝin kapti! — kriis la komercisto al la policisto.

— Kompreneble, sinjoro! — diris la homo kun la flava lado, saltis


antaŭen kaj kriis laŭte:

— He! homoj! kaptu! tien al Nowy Swiat kuris ŝtelistino!

La pordo de la magazeno fermiĝis, la juna sinjoro kun rideto riproĉis


la komerciston, ke pro lia tiel malgranda perdo li faris al si tiom da
klopodoj.

La strato post kelke da sekundoj prezentis scenon bruan kaj


tumultan.

Kiel fulmo tratranĉas la nubojn, tiel la nigre vestita virino rapide


trapuŝiĝadis tra la amasoj da pasantoj, kurante blinde en la direkto
al Nowy Swiat. Kredeble ŝi ne sciis, kien ŝi kuras kaj kien ŝi devas
kuri, ŝi estis senkonscia, duone freneza. En ĉi tiu momento ŝi per la
malgranda konscia resto de siaj pensoj eble bedaŭris, ke ŝi faris
agon malhonoran, sed ŝi jam faris ĝin, kaj terura timo ŝin atakis. Sub
instigo de la instinkto de memkonservo ŝi kuris for de la homoj, kaj
ili estis malantaŭ ŝi, antaŭ ŝi, ĉirkaŭ ŝi; kredeble ŝajnis al ŝi, ke
kurado rapida, blinda, senpripensa alportos ŝin tien, kie ili ne
estos....

La kun ŝi renkontiĝantaj kaj de ŝi dispuŝataj pasantoj komence


rigardis ŝin kun miro aŭ timo, eĉ forflankiĝis antaŭ ŝi, supozante, ke
ŝi estas frenezulino aŭ ke ŝi havas ian urĝegan bezonon rapidi. Sed
baldaŭ sur la strato laŭte eksonis la vorto: kaptu! tuj post ĝi eksonis
alia vorto: ŝtelistino!

Tiuj vortoj ne estis elparolitaj de unu voĉo, sed ruliĝis de tiu sama
flanko, de kiu kuris la virino, transflugante el unu buŝo en alian,
konstante kreskante, kaj akceptante ĉiam pli da forto. La virino, kiu
komencis jam perdi rapidecon en sia kurado kaj lacigite haltis por
sekundo, ekaŭdis la ŝin pelantajn minacajn kriojn.
Samtempe aliĝis al ili ĉiam pli laŭta frapado de homaj piedoj, kiuj
kuris sur la ŝtonoj de la trotuaro. Terura tremo skuis ŝin de la kapo
ĝis la piedoj, ŝi ekkuris pluen kun tia rapideco, kvazaŭ ŝi havus
flugilojn ĉe la brakoj. Ŝi efektive denove havis flugilojn, sed nun ili
konsistis ne el doloro, sed el timo.

Subite ŝi eksentis, ke estas al ŝi malfacile kuri, ne tial, ke mankas al


ŝi fortoj — la flugiloj de la timo ja preskaŭ portis ŝin super la tero —
sed tial, ke homoj, irantaj en la kontraŭa direkto, komencis bari al ŝi
la vojon, etendi la manojn, por kapti ŝian veston. Ŝiaj flugiloj fariĝis
jam ne sole rapidaj, sed ankaŭ elastaj! kaj ĵetadis ŝin en diversaj
direktoj kun miriga elasteco kaj facileco de movoj; ŝi evitadis la
manojn de la pasantoj, ŝi preterfrotadis ilin, sed tamen forkuradis.

Sed baldaŭ montriĝis, ke jam ne apartaj personoj iras al ŝi renkonte,


sed iras kelke da personoj kune kaj okupas la tutan larĝon de la
trotuaro; eviti ilin ne estas eble; troviĝinte antaŭ ili, ŝi certe estos
kaptita de ili.

Ŝi desaltis de la trotuaro; sur la mezo de la strato estas multe da


radoj kaj da ĉevalaj hufoj, sed da homoj piedirantaj estas malpli,
preskaŭ neniom.

Ŝi kuris meze de la strato, ŝi evitadis nun la radojn kaj ĉevalajn


hufojn kun tia sama lerteco, kiel antaŭe la pasantojn. Sed en tiu
sama momento, kiam ŝi ĵetiĝis sur la mezon de la strato, tien ĵetiĝis
post ŝi malluma amaso, konsistanta el ŝin pelantaj homoj. Kiuj estis
tiuj homoj? En la fronto de la kuranta anaro brilis flavaj ladoj; post
ili, kriante kaj ridante, kuris strataj buboj, kiuj ĉiam tre volonte
partoprenas en ĉiu tumulta sceno; post la buboj iris iom malpli
rapide diversaj senlaboruloj, por kiuj ĉia homa amasiĝo prezentas
distraĵon.

La droŝkoj kaj kaleŝoj iom maldensiĝis. La virino haltis meze de la


strato kaj ekrigardis malantaŭen. Kelkaj dekoj da paŝoj apartigis ŝin
ankoraŭ de la nigra maso, kiu konsistis el homaj figuroj kaj kriis per

Ŝ
voĉoj. Ŝi staris nur kelke da sekundoj kaj ekkuris denove rekte
antaŭen. Tiam ankaŭ antaŭ ŝi aperis nigra maso, moviĝanta, tiel
same kiel tiu, kiu estis malantaŭ ŝi, sed havanta alian formon, iom
longa, alta, kun granda okulo en formo de supre lumanta purpura
lanterno. Sonorilo arĝentosona, klara kaj laŭta eksonis en la aero,
sonis longe, akre, averte, la purpura okulo rapide ŝoviĝis antaŭen,
pezaj radoj krakis obtuze, hufoj de ĉevaloj sonis metale, frapante la
tere kuŝantajn ferajn relojn, sur kiuj ruliĝis la radoj.

Tio estis grandega tramvoja omnibuso, tirata de kvar grandaj, fortaj


ĉevaloj, plena de homoj, kun granda kvanto da pezegaj ŝarĝoj.

La virino ne ĉesis kuri meze de la strato; malantaŭ kaj antaŭ ŝi kuris


du nigraj masoj, unu kun krioj kaj mokoj, la dua kun neĉesanta
sonorado, obtuza bruo kaj grandega purpura okulo; ambaŭ ŝoviĝis
en rekta direkto al la virino, kiu kuris inter ili. Se ŝi ne forsaltos
flanken, unu aŭ la dua nepre ŝin englutos. Ŝi deflankiĝis de la rekta
linio, laŭ kiu ŝi kuris ĝis nun, haltis kaj ĵetis rigardon ĉirkaŭen.

Nun la ŝin pelanta amaso da homoj estis jam en la distanco de ne


malpli ol dekkelke da paŝoj de ŝi, kaj tia sama interspaco apartigis
ŝin de la ruliĝanta grandega veturilo. Sed la amaso kuris malpli
rapide ol la veturilo, kiu ruliĝis tre rapide.

Ŝi jam plu ne kuris. Mankis jam al ŝi fortoj, aŭ ŝi decidis en ia ajn


maniero meti finon al tiu terura pelado. Ŝi staris kun brusto turnita al
tiu flanko, de kiu venis la omnibuso, sed la vizaĝon ŝi turnis al tiu
flanko, de kiu kuris la homoj. Nun en ŝiaj okuloj brilis lumo de
konscia penso. Oni povus pensi, ke ŝi faras elekton. Kian elekton?
Sur unu flanko estas malhonoro, mokado, malliberejo, longaj, eble
senfinaj turmentoj, sur la dua estas morto... morto terura, sed
subita, fulma.

Kaj tamen la instinkto de memkonservo videble ne tute ŝin forlasis,


la morto ŝajnis al ŝi pli terura ol la homoj, ĉar antaŭ momento ŝi
deflankiĝis ja de tiu rekta linio, sur kiu kuris al ŝi la liberigonta morto.
Jes, sed nun ŝi denove komencas retiriĝi al tiu linio; la homo kun la
flava lado sur la brusto kurantaŭiĝis el la pelanta amaso, etendis la
manon kaj ektuŝis la randon de ŝia tuko. Ŝi eksaltis, stariĝis sur unu
el la feraj reloj. Kun vizaĝo levita al la malluma ĉielo ŝi etendis
ambaŭ manojn supren. Ŝia buŝo malfermiĝis kaj eligis neklaran
ekkrion. Ĉu ŝi ĵetis al la stelplena ĉielo suferplenan plendon, ĉu ŝi
elĝemis vorton de pardono, ĉu eble la nomon de sia infano? Neniu
klare aŭdis. La homo kun la flava lado sur la brusto, kiun en la unua
momento surprizis la subita flankenĵetiĝo de la virino, denove alkuris
al ŝi kaj kaptis ŝin je la rando de la tuko. Per fulma movo ŝi forĵetis la
tukon kaj lasis ĝin en la mano de la policisto, kaj mem ŝi falis sur la
teron.

— Haltu! haltu! — eksonis terura krio el la maso.

Sed la purpura okulo ne volis obei, ĝi ĉiam flugis antaŭen, kaj la


hufoj de la ĉevaloj frapis sur la feraj reloj.

— Haltu! haltu! — kriis la amaso senĉese kaj kun terura voĉo. La


veturigisto desaltis de sia sidejo, stariĝis, kuntiris per la mano la
longajn kondukŝnurojn, kaj per voĉo raŭka de teruro li kriis al la
ĉevaloj, ke ili haltu.

Ili haltis, sed tiam, kiam peza rado kun malgranda frapo jam
deŝoviĝis de la brusto de la tere kuŝanta virino.

Kun tomba silento staris la amaso meze de la belega strato; la


vizaĝoj, paliĝintaj de teruro, kaj la brustoj malfacile spirantaj de
ekscitiĝo, kliniĝis super la malhela figuro, kiu simile al senmova
makulo kuŝis sur la blanka neĝa sternaĵo.

La rado de la grandega veturilo frakasis la bruston de Marta kaj


elpelis el ĝi la vivon. Ŝia vizaĝo restis netuŝita, kaj per la vitrecaj
okuloj ŝi rigardis la stelplenan ĉielon.
Noto de transskribinto:

Mankintajn punktojn kaj aliajn interpunkciajn mispresaĵojn mi


ĝustigis sen rimarkoj. Kelkaj interpunkciaj aferoj adaptiĝis al la
originala pola teksto, por kroma komprenebleco. Mi registris aliajn
ŝanĝojn per html-aj komentoj. Ankaŭ originalajn paĝkomencojn
mi simile registris.
*** END OF THE PROJECT GUTENBERG EBOOK MARTA ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
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!

ebookname.com

You might also like