The Swift Programming Language Swift 57 Apple Inc download
The Swift Programming Language Swift 57 Apple Inc download
Inc download
https://ebookbell.com/product/the-swift-programming-language-
swift-57-apple-inc-50090374
https://ebookbell.com/product/the-swift-programming-language-
swift-57-57-apple-inc-44480436
https://ebookbell.com/product/the-swift-programming-language-
swift-53-apple-inc-34614756
https://ebookbell.com/product/the-swift-programming-language-
swift-55-apple-inc-36444848
https://ebookbell.com/product/mastering-swift-53-upgrade-your-
knowledge-and-become-an-expert-in-the-latest-version-of-the-swift-
programming-language-6th-edition-jon-hoffman-22069006
The Swift Programming Language Swift 21 Apple Inc
https://ebookbell.com/product/the-swift-programming-language-
swift-21-apple-inc-57954152
https://ebookbell.com/product/the-swift-programming-language-
swift-4-apple-inc-7177452
https://ebookbell.com/product/the-swift-programming-language-inc-
apple-22130798
https://ebookbell.com/product/the-swift-programming-language-apple-
inc-34614754
https://ebookbell.com/product/the-swift-programming-language-
prerelease-apple-inc-4690428
Welcome to Swift
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
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.
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
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.
If the initial value doesn’t provide enough information (or if there isn’t
an initial value), specify the type by writing it after the variable,
separated by a colon.
1 let implicitInteger = 70
2 let implicitDouble = 70.0
3 let explicitDouble: Double = 70
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:
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.
1 fruits.append("blueberries")
2 print(fruits)
1 fruits = []
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.
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.
EXPERIMENT
Change optionalName to nil. What greeting do you get? Add an else clause
that sets a different greeting if optionalName is nil.
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 }
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.
EXPERIMENT
Replace the _ with a variable name, and keep track of which kind of number
was the largest.
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.
EXPERIMENT
Remove the day parameter. Add a parameter to include today’s lunch special
in the greeting.
Functions are a first-class type. This means that a function can return
another function as its value.
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.
EXPERIMENT
Add a constant property with let, and add another method that takes an
argument.
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).
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.
In the setter for perimeter, the new value has the implicit name
newValue. You can provide an explicit name in parentheses after set.
Notice that the initializer for the EquilateralTriangle class has three
different steps:
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.
When working with optional values, you can write ? before operations
like methods, properties, and subscripting. If the value before the ? is
nil, everything after the ? is ignored and the value of the whole
expression is nil. Otherwise, the optional value is unwrapped, and
everything after the ? acts on the unwrapped value. In both cases, the
value of the whole expression is an optional value.
Write a function that compares two Rank values by comparing their raw
values.
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
EXPERIMENT
Notice how the sunrise and sunset times are extracted from the
ServerResponse value as part of matching the value against the
switch cases.
1 struct Card {
2 var rank: Rank
3 var suit: Suit
4 func simpleDescription() -> String {
5 return "The \(rank.simpleDescription()) of \
(suit.simpleDescription())"
6 }
7 }
8 let threeOfSpades = Card(rank: .three, suit:
.spades)
9 let threeOfSpadesDescription =
threeOfSpades.simpleDescription()
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 Task {
2 await connectUser(to: "primary")
3 }
4 // Prints "Hello Guest, user ID 97"
1 protocol ExampleProtocol {
2 var simpleDescription: String { get }
3 mutating func adjust()
4 }
EXPERIMENT
EXPERIMENT
Write an extension for the Double type that adds an absoluteValue property.
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.
Error Handling
You represent errors using any type that adopts the Error protocol.
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.
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,
toPrinter: "Bi Sheng")
3 print(printerResponse)
4 } catch {
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.
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?
Generics
Write a name inside angle brackets to make a generic function or
type.
EXPERIMENT
1 let maximumNumberOfLoginAttempts = 10
2 var currentLoginAttempt = 0
NOTE
Type Annotations
You can provide a type annotation when you declare a constant or
variable, to be clear about the kind of values the constant or variable
can store. Write a type annotation by placing a colon after the
constant or variable name, followed by a space, followed by the name
of the type to use.
The colon in the declaration means “…of type…,” so the code above
can be read as:
The phrase “of type String” means “can store any String value.”
Think of it as meaning “the type of thing” (or “the kind of thing”) that
can be stored.
welcomeMessage = "Hello"
You can define multiple related variables of the same type on a single
line, separated by commas, with a single type annotation after the
final variable name:
NOTE
It’s rare that you need to write type annotations in practice. If you provide an
initial value for a constant or variable at the point that it’s defined, Swift can
almost always infer the type to be used for that constant or variable, as
described in Type Safety and Type Inference. In the welcomeMessage
example above, no initial value is provided, and so the type of the
welcomeMessage variable is specified with a type annotation rather than being
inferred from an initial value.
1 let π = 3.14159
2 let 你好 = "你好世界"
3 let 🐶 🐮 = "dogcow"
Constant and variable names can’t contain whitespace characters,
mathematical symbols, arrows, private-use Unicode scalar values, or
line- and box-drawing characters. Nor can they begin with a number,
although numbers may be included elsewhere within the name.
NOTE
If you need to give a constant or variable the same name as a reserved Swift
keyword, surround the keyword with backticks (`) when using it as a name.
However, avoid using keywords as names unless you have absolutely no
choice.
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.
ebookbell.com