Swift Programing
Swift Programing
The Basics
Work with common kinds of data and write basic syntax.
https://docs.swift.org/swift-book/documentation/the-swift-
programming-language/thebasics/
The Basics
Work with common kinds of data and write basic
syntax.
if environment == "development" {
maximumNumberOfLoginAttempts = 100
} else {
maximumNumberOfLoginAttempts = 10
}
.
Type Annotations
Semicolons
Unlike many other languages, Swift doesn’t require
you to write a semicolon (;) after each statement in
your code, although you can do so if you wish.
However, semicolons are required if you want to
write multiple separate statements on a single line:
let cat = "🐱"; print(cat)
// Prints "🐱"
Integers
Integers are whole numbers with no fractional
component, such as 42 and -23. Integers are
.
Integer Bounds
Int
as Int32.
On a 64-bit platform, Int is the same size
as Int64.
Unless you need to work with a specific size of
integer, always use Int for integer values in your
.
UInt
as UInt32.
On a 64-bit platform, UInt is the same size
as UInt64.
Note
Use UInt only when you specifically need an
unsigned integer type with the same size as the
platform’s native word size. If this isn’t the
case, Int is preferred, even when the values to be
stored are known to be nonnegative. A consistent
use of Int for integer values aids code
interoperability, avoids the need to convert between
different number types, and matches integer type
inference, as described in Type Safety and Type
Inference.
Floating-Point Numbers
Floating-point numbers are numbers with a
fractional component, such as 3.14159, 0.1, and -
273.15.
.
Note
Double has a precision of at least 15 decimal digits,
whereas the precision of Float can be as little as 6
decimal digits. The appropriate floating-point type to
use depends on the nature and range of values you
need to work with in your code. In situations where
either type would be appropriate, Double is
preferred.
Type Safety and Type Inference
Swift is a type-safe language. A type safe language
encourages you to be clear about the types of values
your code can work with. If part of your code
requires a String, you can’t pass it an Int by
mistake.
Because Swift is type safe, it performs type
checks when compiling your code and flags any
mismatched types as errors. This enables you to
catch and fix errors as early as possible in the
development process.
Type-checking helps you avoid errors when you’re
working with different types of values. However, this
doesn’t mean that you have to specify the type of
.
Numeric Literals
Integer literals can be written as:
A decimal number, with no prefix
Integer Conversion
Once you define a type alias, you can use the alias
anywhere you might use the original name:
var maxAmplitudeFound = AudioSample.min
.
// maxAmplitudeFound is now 0
Booleans
Swift has a basic Boolean type, called Bool.
Boolean values are referred to as logical, because
they can only ever be true or false. Swift provides
two Boolean constant values, true and false:
let orangesAreOrange = true
let turnipsAreDelicious = false
The types
of orangesAreOrange and turnipsAreDelicious hav
e been inferred as Bool from the fact that they were
initialized with Boolean literal values. As
with Int and Double above, you don’t need to
declare constants or variables as Bool if you set
them to true or false as soon as you create them.
Type inference helps make Swift code more concise
and readable when it initializes constants or
variables with other values whose type is already
known.
Boolean values are particularly useful when you
work with conditional statements such as
the if statement:
if turnipsAreDelicious {
print("Mmm, tasty turnips!")
} else {
print("Eww, turnips are horrible.")
}
.
Tuples
Tuples group multiple values into a single compound
value. The values within a tuple can be of any type
and don’t have to be of the same type as each other.
In this example, (404, "Not Found") is a tuple that
describes an HTTP status code. An HTTP status
code is a special value returned by a web server
whenever you request a web page. A status code
.
nil
if convertedNumber != nil {
print("convertedNumber contains some integer value.")
}
// Prints "convertedNumber contains some integer value."
it’s nil.
Propagate the nil value, by returning nil or
Note
In Objective-C, nil is a pointer to a nonexistent
object. In Swift, nil isn’t a pointer — it’s the
absence of a value of a certain type. Optionals
of any type can be set to nil, not just object types.
Optional Binding
Force Unwrapping
Error Handling
You use error handling to respond to error
conditions your program may encounter during
execution.
In contrast to optionals, which can use the presence
or absence of a value to communicate success or
failure of a function, error handling allows you to
determine the underlying cause of failure, and, if
necessary, propagate the error to another part of
your program.
.
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.outOfCleanDishes {
washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
buyGroceries(ingredients)
}
Enforcing Preconditions