The Swift Programming Language Swift 5 7 Apple Inc. download
The Swift Programming Language Swift 5 7 Apple Inc. download
https://ebookmeta.com/product/the-swift-programming-language-
swift-5-7-apple-inc/
https://ebookmeta.com/product/deep-learning-with-swift-for-
tensorflow-differentiable-programming-with-swift-1st-edition-
rahul-bhalley/
https://ebookmeta.com/product/swift-3-protocol-oriented-
programming-hoffman-jon/
https://ebookmeta.com/product/develop-in-swift-explorations-
xcode-13-2021-13th-edition-apple-education/
https://ebookmeta.com/product/community-based-learning-and-
social-movements-popular-education-in-a-populist-age-1st-edition-
marjorie-mayo/
Mobilizing Narratives Narrating Injustices of Im
Mobility 1st Edition Hager Ben Driss (Editor)
https://ebookmeta.com/product/mobilizing-narratives-narrating-
injustices-of-im-mobility-1st-edition-hager-ben-driss-editor/
https://ebookmeta.com/product/spectres-of-reparation-in-south-
africa-1st-edition-jaco-barnard-naude/
https://ebookmeta.com/product/acing-the-ccna-exam-
meap-v03-jeremy-mcdowell/
https://ebookmeta.com/product/a-broad-guide-to-reading-and-
comprehension-1st-edition-mahmoud-sultan-nafa/
Unraveling Remaking Personhood in a Neurodiverse Age
1st Edition Wolf-Meyer
https://ebookmeta.com/product/unraveling-remaking-personhood-in-
a-neurodiverse-age-1st-edition-wolf-meyer/
Welcome to Swift
About Swift
Swift is a fantastic way to write software, whether it’s for phones,
desktops, servers, or anything else that runs code. It’s a safe, fast,
and interactive programming language that combines the best in
modern language thinking with wisdom from the wider Apple
engineering culture and the diverse contributions from its open-
source community. The compiler is optimized for performance and
the language is optimized for development, without compromising
on either.
Swift code is compiled and optimized to get the most out of modern
hardware. The syntax and standard library have been designed
based on the guiding principle that the obvious way to write your
code should also perform the best. Its combination of safety and
speed make Swift an excellent choice for everything from “Hello,
world!” to an entire operating system.
Swift has been years in the making, and it continues to evolve with
new features and capabilities. Our goals for Swift are ambitious. We
can’t wait to see what you create with it.
Version Compatibility
This book describes Swift 5.7, the default version of Swift that’s
included in Xcode 14. You can use Xcode 14 to build targets that are
written in either Swift 5.7, Swift 4.2, or Swift 4.
When you use Xcode 14 to build Swift 4 and Swift 4.2 code, most
Swift 5.7 functionality is available. That said, the following changes
are available only to code that uses Swift 5.7 or later:
1 print("Hello, world!")
2 // Prints "Hello, world!"
This tour gives you enough information to start writing code in Swift
by showing you how to accomplish a variety of programming tasks.
Don’t worry if you don’t understand something—everything
introduced in this tour is explained in detail in the rest of this book.
NOTE
On a Mac with Xcode installed, or on an iPad with Swift Playgrounds, you can
open this chapter as a playground. Playgrounds allow you to edit the code
listings and see the result immediately.
Download Playground
Simple Values
Use let to make a constant and var to make a variable. The value
of a constant doesn’t need to be known at compile time, but you
must assign it a value exactly once. This means you can use
constants to name a value that you determine once but use in many
places.
1 var myVariable = 42
2 myVariable = 50
3 let myConstant = 42
A constant or variable must have the same type as the value you
want to assign to it. However, you don’t always have to write the
type explicitly. Providing a value when you create a constant or
variable lets the compiler infer its type. In the example above, the
compiler infers that myVariable is an integer because its initial value
is an integer.
1 let implicitInteger = 70
2 let implicitDouble = 70.0
EXPERIMENT
EXPERIMENT
Try removing the conversion to String from the last line. What error do you
get?
1 let apples = 3
2 let oranges = 5
3 let appleSummary = "I have \(apples) apples."
4 let fruitSummary = "I have \(apples + oranges) pieces
of fruit."
EXPERIMENT
Use three double quotation marks (""") for strings that take up
multiple lines. Indentation at the start of each quoted line is
removed, as long as it matches the indentation of the closing
quotation marks. For example:
1 let quotation = """
2 I said "I have \(apples) apples."
Create arrays and dictionaries using brackets ([]), and access their
elements by writing the index or key in brackets. A comma is
allowed after the last element.
4 var occupations = [
5 "Malcolm": "Captain",
6 "Kaylee": "Mechanic",
7 ]
8 occupations["Jayne"] = "Public Relations"
1 shoppingList.append("blue paint")
2 print(shoppingList)
1 shoppingList = []
2 occupations = [:]
Control Flow
Use if and switch to make conditionals, and use for-in, while, and
repeat-while to make loops. Parentheses around the condition or
loop variable are optional. Braces around the body are required.
6 } else {
7 teamScore += 1
8 }
9 }
10 print(teamScore)
11 // Prints "11"
You can use if and let together to work with values that might be
missing. These values are represented as optionals. An optional
value either contains a value or contains nil to indicate that a value
is missing. Write a question mark (?) after the type of a value to
mark the value as optional.
3 // Prints "false"
4
5 var optionalName: String? = "John Appleseed"
9 }
EXPERIMENT
If the optional value is nil, the conditional is false and the code in
braces is skipped. Otherwise, the optional value is unwrapped and
assigned to the constant after let, which makes the unwrapped
value available inside the block of code.
You can use a shorter spelling to unwrap a value, using the same
name for that unwrapped value.
1 if let nickname {
2 print("Hey, \(nickname)")
3 }
3 case "celery":
4 print("Add some raisins and make ants on a log.")
5 case "cucumber", "watercress":
9 default:
10 print("Everything tastes good in soup.")
11 }
Notice how let can be used in a pattern to assign the value that
matched the pattern to a constant.
After executing the code inside the switch case that matched, the
program exits from the switch statement. Execution doesn’t continue
to the next case, so you don’t need to explicitly break out of the
switch at the end of each case’s code.
6 var largest = 0
7 for (_, numbers) in interestingNumbers {
8 for number in numbers {
12 }
13 }
14 print(largest)
15 // Prints "25"
EXPERIMENT
Replace the _ with a variable name, and keep track of which kind of number
was the largest.
3 n *= 2
4 }
5 print(n)
6 // Prints "128"
7
8 var m = 2
9 repeat {
10 m *= 2
11 } while m < 100
12 print(m)
13 // Prints "128"
1 var total = 0
2 for i in 0..<4 {
3 total += i
4 }
5 print(total)
6 // Prints "6"
Use ..< to make a range that omits its upper value, and use ... to
make a range that includes both values.
Functions and Closures
Use func to declare a function. Call a function by following its name
with a list of arguments in parentheses. Use -> to separate the
parameter names and types from the function’s return type.
3 }
4 greet(person: "Bob", day: "Tuesday")
EXPERIMENT
Remove the day parameter. Add a parameter to include today’s lunch special
in the greeting.
3 }
4 greet("John", on: "Wednesday")
5
6 for score in scores {
7 if score > max {
8 max = score
9 } else if score < min {
10 min = score
11 }
12 sum += score
13 }
14
15 return (min, max, sum)
16 }
19 // Prints "120"
20 print(statistics.2)
21 // Prints "120"
3 func add() {
4 y += 5
5 }
6 add()
7 return y
8 }
9 returnFifteen()
3 return 1 + number
4 }
5 return addOne
6 }
7 var increment = makeIncrementer()
8 increment(7)
5 }
6 }
7 return false
8 }
9 func lessThanTen(number: Int) -> Bool {
10 return number < 10
11 }
12 var numbers = [20, 19, 7, 12]
13 hasAnyMatches(list: numbers, condition: lessThanTen)
4 })
EXPERIMENT
You have several options for writing closures more concisely. When a
closure’s type is already known, such as the callback for a delegate,
you can omit the type of its parameters, its return type, or both.
Single statement closures implicitly return the value of their only
statement.
number })
2 print(mappedNumbers)
3 // Prints "[60, 57, 21, 36]"
1 class Shape {
2 var numberOfSides = 0
6 }
EXPERIMENT
Add a constant property with let, and add another method that takes an
argument.
2 shape.numberOfSides = 7
3 var shapeDescription = shape.simpleDescription()
6 self.name = name
7 }
8
11 }
12 }
Notice how self is used to distinguish the name property from the
name argument to the initializer. The arguments to the initializer are
passed like a function call when you create an instance of the class.
Every property needs a value assigned—either in its declaration (as
with numberOfSides) or in the initializer (as with name).
3
4 init(sideLength: Double, name: String) {
5 self.sideLength = sideLength
6 super.init(name: name)
7 numberOfSides = 4
8 }
9
10 func area() -> Double {
11 return sideLength * sideLength
12 }
13
14 override func simpleDescription() -> String {
17 }
18 let test = Square(sideLength: 5.2, name: "my test
square")
19 test.area()
20 test.simpleDescription()
EXPERIMENT
Make another subclass of NamedShape called Circle that takes a radius and
a name as arguments to its initializer. Implement an area() and a
simpleDescription() method on the Circle class.
3
4 init(sideLength: Double, name: String) {
5 self.sideLength = sideLength
6 super.init(name: name)
7 numberOfSides = 3
8 }
9
10 var perimeter: Double {
11 get {
18
19 override func simpleDescription() -> String {
20 return "An equilateral triangle with sides
of length \(sideLength)."
21 }
22 }
26 triangle.perimeter = 9.9
27 print(triangle.sideLength)
28 // Prints "3.3000000000000003"
In the setter for perimeter, the new value has the implicit name
newValue. You can provide an explicit name in parentheses after set.
If you don’t need to compute the property but still need to provide
code that’s run before and after setting a new value, use willSet
and didSet. The code you provide is run any time the value changes
outside of an initializer. For example, the class below ensures that
the side length of its triangle is always the same as the side length
of its square.
1 class TriangleAndSquare {
2 var triangle: EquilateralTriangle {
3 willSet {
4 square.sideLength = newValue.sideLength
5 }
6 }
7 var square: Square {
8 willSet {
9 triangle.sideLength = newValue.sideLength
10 }
11 }
14 triangle = EquilateralTriangle(sideLength:
size, name: name)
15 }
16 }
17 var triangleAndSquare = TriangleAndSquare(size: 10,
name: "another test shape")
18 print(triangleAndSquare.square.sideLength)
19 // Prints "10.0"
20 print(triangleAndSquare.triangle.sideLength)
21 // Prints "10.0"
22 triangleAndSquare.square = Square(sideLength: 50,
name: "larger square")
23 print(triangleAndSquare.triangle.sideLength)
24 // Prints "50.0"
5
6 func simpleDescription() -> String {
7 switch self {
8 case .ace:
9 return "ace"
10 case .jack:
11 return "jack"
12 case .queen:
13 return "queen"
14 case .king:
15 return "king"
16 default:
17 return String(self.rawValue)
18 }
19 }
20 }
21 let ace = Rank.ace
22 let aceRawValue = ace.rawValue
EXPERIMENT
Write a function that compares two Rank values by comparing their raw
values.
2 let threeDescription =
convertedRank.simpleDescription()
3 }
3
4 func simpleDescription() -> String {
5 switch self {
6 case .spades:
7 return "spades"
8 case .hearts:
9 return "hearts"
10 case .diamonds:
11 return "diamonds"
12 case .clubs:
13 return "clubs"
14 }
15 }
16 }
17 let hearts = Suit.hearts
EXPERIMENT
Add a color() method to Suit that returns “black” for spades and clubs,
and returns “red” for hearts and diamonds.
Notice the two ways that the hearts case of the enumeration is
referred to above: When assigning a value to the hearts constant,
the enumeration case Suit.hearts is referred to by its full name
because the constant doesn’t have an explicit type specified. Inside
the switch, the enumeration case is referred to by the abbreviated
form .hearts because the value of self is already known to be a
suit. You can use the abbreviated form anytime the value’s type is
already known.
3 case failure(String)
4 }
5
cheese.")
8
9 switch success {
EXPERIMENT
Notice how the sunrise and sunset times are extracted from the
ServerResponse value as part of matching the value against the
switch cases.
Use struct to create a structure. Structures support many of the
same behaviors as classes, including methods and initializers. One of
the most important differences between structures and classes is
that structures are always copied when they’re passed around in
your code, but classes are passed by reference.
1 struct Card {
2 var rank: Rank
(suit.simpleDescription())"
6 }
7 }
EXPERIMENT
Write a function that returns an array containing a full deck of cards, with
one card of each combination of rank and suit.
Concurrency
Use async to mark a function that runs asynchronously.
1 func fetchUserID(from server: String) async -> Int {
2 if server == "primary" {
3 return 97
4 }
5 return 501
6 }
5 }
6 return "Guest"
7 }
5 print(greeting)
6 }
1 Task {
1 protocol ExampleProtocol {
2 var simpleDescription: String { get }
class."
3 var anotherProperty: Int = 69105
4 func adjust() {
8 var a = SimpleClass()
9 a.adjust()
10 let aDescription = a.simpleDescription
11
12 struct SimpleStructure: ExampleProtocol {
13 var simpleDescription: String = "A simple
structure"
14 mutating func adjust() {
15 simpleDescription += " (adjusted)"
16 }
17 }
18 var b = SimpleStructure()
19 b.adjust()
20 let bDescription = b.simpleDescription
EXPERIMENT
8 }
9 print(7.simpleDescription)
10 // Prints "The number 7"
EXPERIMENT
You can use a protocol name just like any other named type—for
example, to create a collection of objects that have different types
but that all conform to a single protocol. When you work with values
whose type is a protocol type, methods outside the protocol
definition aren’t available.
2 print(protocolValue.simpleDescription)
3 // Prints "A very simple class. Now 100% adjusted."
4 // print(protocolValue.anotherProperty) // Uncomment
Error Handling
You represent errors using any type that adopts the Error protocol.
1 enum PrinterError: Error {
2 case outOfPaper
3 case noToner
4 case onFire
5 }
Use throw to throw an error and throws to mark a function that can
throw an error. If you throw an error in a function, the function
returns immediately and the code that called the function handles
the error.
3 throw PrinterError.noToner
4 }
5 return "Job sent"
6 }
There are several ways to handle errors. One way is to use do-catch.
Inside the do block, you mark code that can throw an error by
writing try in front of it. Inside the catch block, the error is
automatically given the name error unless you give it a different
name.
1 do {
2 let printerResponse = try send(job: 1040,
5 print(error)
6 }
7 // Prints "Job sent"
EXPERIMENT
You can provide multiple catch blocks that handle specific errors.
You write a pattern after catch just as you do after case in a switch.
1 do {
2 let printerResponse = try send(job: 1440,
toPrinter: "Gutenberg")
3 print(printerResponse)
4 } catch PrinterError.onFire {
10 }
11 // Prints "Job sent"
EXPERIMENT
Add code to throw an error inside the do block. What kind of error do you
need to throw so that the error is handled by the first catch block? What
about the second and third blocks?
3
4 func fridgeContains(_ food: String) -> Bool {
5 fridgeIsOpen = true
6 defer {
7 fridgeIsOpen = false
8 }
9
10 let result = fridgeContent.contains(food)
11 return result
12 }
13 fridgeContains("banana")
14 print(fridgeIsOpen)
15 // Prints "false"
Generics
Write a name inside angle brackets to make a generic function or
type.
1 func makeArray<Item>(repeating item: Item,
numberOfTimes: Int) -> [Item] {
5 }
6 return result
7 }
2 enum OptionalValue<Wrapped> {
3 case none
4 case some(Wrapped)
5 }
6 var possibleInteger: OptionalValue<Int> = .none
7 possibleInteger = .some(100)
7 return true
8 }
9 }
10 }
11 return false
12 }
EXPERIMENT
"Lady Ellis, understand one thing--that this is a matter you must not
interfere in. The housekeeping at the Red Court Farm that you are
pleased to find cause of fault with--is an established rule; so to say,
an institution. It cannot be changed. Sinnett will conduct it as
hitherto without trouble to or interference from yourself. Whenever it
does not please you to sit down to table, there are other rooms in
which you can order your dinner served."
Lady Ellis tapped her foot on the soft carpet. "Do you consider that
there is any reason in keeping so large a table?"
"I think your sons have been brought up to a great deal that is
unfitting. One would think they were lords."
"I do not see that it can be avoided. I give certain orders. Sinnett,
acting under you, opposes them. What can the result be but
unseemly contention? How would you avoid it, I ask?"
"By going to live in one of the cottages on the heath, and leaving
Isaac--I mean Richard--master of the Red Court Farm."
Mr. Thornycroft brought down his hand, not in anger but emphasis,
on the small breakfast table.
Lady Ellis sipped her coffee. It did not appear safe to say more. A
cottage on the heath, or lodgings at Jutpoint!
"I cannot think what possible pleasure you can find in the society of
such men," she said, after a pause. "Look at them, coming out to
dinner in those rough coats!"
"I fancied you left them early; I thought I saw you cross the garden,
as if coming from the plateau," she said, resolving to speak of the
matter which had so puzzled her.
"I was wide awake. It was just before that mist came on," she
added.
"Ah, the fault must have lain in the mist. I have known it come as a
mirage occasionally, bringing deception and confusion."
Did he really mean it? It seemed so, for there was seriousness on his
face as he spoke. Quitting the room, he descended the stairs, and
made his way to the fields. In the four-acre mead--as it was called in
common parlance on the farm--he came upon Richard watching the
hay-makers. Richard wished him good morning; abroad early, it was
the first time he had seen his father that day.
"What was the failure, Dick?" asked the justice. "Fog," shortly
answered Richard. "Couldn't see the light."
"You will not have it again. Sinnett holds my orders, and my wife has
been made aware she does. There's no need for you to put yourself
out."
With the injunction, spoken rather testily, Mr. Thornycroft left him.
But a little later, when he met Isaac, he voluntarily entered on the
subject; hinting his vexation at the past, promising that it would
never again occur, almost as if he were tendering an apology for the
accident.
"I'm afraid I made a mistake, Ikey; I'm afraid I made a mistake; but
I meant it for the best."
It was ever thus. To his second son Mr. Thornycroft's behaviour was
somewhat different from what it was to his eldest. It could not be
said that he paid him more deference: but it was to Isaac he
generally spoke of business, when speaking was needed; if an
opinion was required, Isaac's was sought in preference to Richard's.
It was just as though Isaac had been the eldest son. That Richard
had brought this on himself, by his assumption of authority, was
quite probable: and the little preference seemed to spring from the
justice involuntarily.
The evening supper took place, and the guests were consoled by the
ample table for the scantiness of the previous dinner. My lady was
not invited to join it; nothing appeared further from Mr. Thornycroft's
thoughts than to have ladies at table. She spent a solitary sort of
evening; Mary Anne was at Mrs. Wilkinson's, taking leave of Miss
Derode.
Was it, she asked herself, to go on like this always and always? Had
she become the wife of Justice Thornycroft only to die of the dreary
life at the Red Court Farm? Let us give her her due. When she
married him she did intend to do her duty as an honest woman, and
send ridiculous flirtations, such as that carried on with Robert Lake,
to the winds. But she did not expect to be done to death of ennui.
A short while went on. Nearly open warfare set in between Mary
Anne and her stepmother. To-day my lady would be harsh, exacting,
almost cruel in her rule; tomorrow the girl would be wholly
neglected--suffered to run wild. Mr. Thornycroft saw that things
could not continue thus, and the refrain of the words he had spoken
to Isaac beat ever on his brain, day by day bringing greater force to
them: "I fear I made a mistake; I fear I made a mistake."
She had come with one of her tales of woe. She had come to beg
and pray to be sent to school. What a change! Mr. Thornycroft was
nearly at his wits' end.
Ere the day was over, his wife brought a complaint to him on her
own score: not altogether of Mary Anne. She simply said,
incidentally, that ill-trained young lady was getting quite beyond her
control, and therefore she must wash her hands of her. The
complaint was of her own health; it appeared to be failing her in a
rather remarkable manner, certainly a sudden one. This was true.
She had concluded that the air of Coastdown was inimical to her, she
wished it might be managed for her to live away--say Cheltenham,
or some other healthy place.
END OF VOL. I.
*** END OF THE PROJECT GUTENBERG EBOOK THE RED COURT
FARM: A NOVEL (VOL. 1 OF 2) ***
Updated editions will replace the previous one—the old editions will
be renamed.
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.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.
• 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 comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
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.
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.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.