• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/43

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

43 Cards in this Set

  • Front
  • Back

Constants and Variables

Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type (such as the number 10 or the string "Hello"). The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future.

Declaring Constants and Variables

Constants and variables must be declared before they are used. You declare constants with the let keyword and variables with the var keyword. Here’s an example of how constants and variables can be used to track the number of login attempts a user has made:




let maximumNumberOfLoginAttempts = 10var currentLoginAttempt = 0




This code can be read as:“Declare a new constant called maximumNumberOfLoginAttempts, and give it a value of 10. Then, declare a new variable called currentLoginAttempt, and give it an initial value of 0.”




In this example, the maximum number of allowed login attempts is declared as a constant, because the maximum value never changes. The current login attempt counter is declared as a variable, because this value must be incremented after each failed login attempt.




You can declare multiple constants or multiple variables on a single line, separated by commas:




var x = 0.0, y = 0.0, z = 0.0




**NOTE** If a stored value in your code is not going to change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.

TYPES

a construct to represent different kinds of data likeletters or numbers commands, special words, and punctuation you use to puttogether a program

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.




var welcomeMessage: String




The colon in the declaration means “…of type…,” so the code above can be read as:“Declare a variable called welcomeMessage that is of type String.”




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.




The welcomeMessage variable can now be set to any string value without error:




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:




var red, green, blue: Double




***NOTE*** It is 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 is defined, Swift can almost always infer the type to be used for that constant or variable



Naming Constants and Variables

Constant and variable names can contain almost any character, including Unicode characters.




Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters.




Nor can they begin with a number, although numbers may be included elsewhere within the name.




Once you’ve declared a constant or variable of a certain type, you can’t redeclare it again with the same name, or change it to store values of a different type.




Nor can you change a constant into a variable or a variable into a constant.




***NOTE*** If you need to give a constant or variable the same name as a reserved Swift keyword, surround the keyword with back ticks (`) when using it as a name. However, avoid using keywords as names unless you have absolutely no choice.

Naming Constants and Variables


(continued)

You can change the value of an existing variable to another value of a compatible type. In this example, the value of friendlyWelcome is changed from "Hello!" to "Bonjour!":




var friendlyWelcome = "Hello!"


friendlyWelcome = "Bonjour!"




// friendlyWelcome is now "Bonjour!"




Unlike a variable, the value of a constant cannot be changed once it is set. Attempting to do so is reported as an error when your code is compiled:




let languageName = "Swift"


languageName = "Swift++"




// this is a compile-time error - languageName cannot be changed

Comments

Single-line comments begin with two forward-slashes (//):




// this is a comment




Multiline comments start with a forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward-slash (*/):




/* this is also a comment, but written over


multiple lines */

Nested Multiline Comments

You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed, followed by the first block:




/* this is the start of the first multiline comment /* this is the second, nested multiline comment */ this is the end of the first multiline comment */




Nested multiline comments enable you to comment out large blocks of code quickly and easily, even if the code already contains multiline comments.

Semicolons

Unlike many other languages, Swift does not 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 "🐱"

Int

Integers are whole numbers with no fractional component, such as 42 and -23. Integers are either signed (positive, zero, or negative) or unsigned (positive or zero).

Floating-Point Numbers

Floating-point numbers are numbers with a fractional component, such as 3.14159, 0.1, and -273.15.




Floating-point types can represent a much wider range of values than integer types, and can store numbers that are much larger or smaller than can be stored in an Int. Swift provides two signed floating-point number types:




Double represents a 64-bit floating-


point number.


Float represents a 32-bit floating-point


number.




***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.

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




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.")


}




// Prints "Eww, turnips are horrible."

Operator

An operator is a special symbol or phrase that you use to check, change, or combine values. For example, the addition operator (+) adds two numbers, as in let i = 1 + 2, and the logical AND operator (&&) combines two Boolean values, as in




if enteredDoorCode && passedRetinaScan.

Operators are


unary , binary , or ternary

Operators are unary, binary, or ternary:




Unary operators operate on a single target (such as - a). Unary prefix operators appear immediately before their target (such as ! b), and unary postfix operators appear immediately after their target (such as c !).




Binary operators operate on two targets (such as 2 + 3) and are infix because they appear in between their two targets.




Ternary operators operate on three targets. Like C, Swift has only one ternary operator, the ternary conditional operator (a ? b : c).




The values that operators affect are operands. In the expression 1 + 2, the + symbol is a binary operator and its two operands are the values 1 and 2.

Unary Operators

++ is the increment operator




lets say you design a game and you want the players to gain a point after a shot




var levelScore = 0


levelScore = levelScore + 1




var totalScore = levelScore


totalScore = ++levelScore




place the ++ operator to the left of the operand.




-- is the decrement operator




*** Note*** the ++ increment operator and -- decrement operator only increase and decrease by 1.

Assignment Operator

The assignment operator (a = b) initializes or updates the value of a with the value of b:



let b = 10


var a = 5


a = b



// a is now equal to 10

Arithmetic Operators

Swift supports the four standard arithmetic operators for all number types:




Addition (+)


Subtraction (-)


Multiplication (*)


Division (/)




1 + 2 // equals 3


5 - 3 // equals 2


2 * 3 // equals 6


10.0 / 2.5 // equals 4.0




The addition operator is also supported for String concatenation:




"hello, " + "world"




// equals "hello, world"

Remainder Operator

The remainder operator (a % b) works out how many multiples of b will fit inside a and returns the value that is left over (known as the remainder).




9 % 4 // equals 1


-9 % 4 // equals -1




Swift’s remainder operator can also operate on floating-point numbers:




8 % 2.5 // equals 0.5




***NOTE*** The remainder operator (%) is also known as a modulo operator in other languages. However, its behavior in Swift for negative numbers means that it is, strictly speaking, a remainder rather than a modulo operation.

Operator Precedence

Swift assigns a priority or precedence to each operator.




Precedence Level: 150


Multiplication: *


Division: /


Remainder: %




Precedence Level: 140


Addition: +


Subtraction: -




If they have the same priority, then work from left to right. ORDER OF OPERATIONS.




var x = 100 + 100 - 3 % 4 * 12 - 2





Comparison Operators

Swift supports all standard C comparison operators:


Equal to (a == b)


Not equal to (a != b)


Greater than (a > b)


Less than (a < b)


Greater than or equal to (a >= b)


Less than or equal to (a <= b)




Each of the comparison operators returns a Bool value to indicate whether or not the statement is true:




1 == 1 // true because 1 is equal to 1


2 != 1 // true because 2 is not equal to 1


2 > 1 // true because 2 is greater than 1


1 < 2 // true because 1 is less than 2


1 >= 1 // true because 1 is greater than or


equal to 1


2 <= 1 // false because 2 is not less than or


equal to 1






***NOTE*** Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance.

Comparison Operators in if statements

Comparison operators are often used in conditional statements, such as the if statement:




let name = "world"


if name == "world" {


print("hello, world")


} else {


print("I'm sorry \(name), but I don't recognize you")


}




// prints "hello, world", because name is indeed equal to "world"

Logical Operators

Logical operators modify or combine the Boolean logic values true and false. Swift supports the three standard logical operators found in C-based languages:




Logical NOT ( ! a )


Logical AND ( a && b )


Logical OR ( a || b )

Logical NOT Operator


!

The logical NOT operator ( !a ) inverts a Boolean value so that true becomes false, and false becomes true.




The logical NOT operator is a prefix operator, and appears immediately before the value it operates on, without any white space. It can be read as “not a, as seen in the following example:




let allowedEntry = false


if !allowedEntry {


print("ACCESS DENIED")


}




// Prints "ACCESS DENIED"




The phrase if !allowedEntry can be read as “if not allowed entry.” The subsequent line is only executed if “not allowed entry” is true; that is, if allowedEntry is false.

Logical AND Operator


&&

The logical AND operator (a && b) creates logical expressions where both values must be true for the overall expression to also be true.




If either value is false, the overall expression will also be false. In fact, if the first value is false, the second value won’t even be evaluated, because it can’t possibly make the overall expression equate to true. This is known as short-circuit evaluation.




This example considers two Bool values and only allows access if both values are true:




let enteredDoorCode = true


let passedRetinaScan = false




if enteredDoorCode && passedRetinaScan {


print("Welcome!")


} else {


print("ACCESS DENIED")}




// Prints "ACCESS DENIED"

Logical OR Operator


||

The logical OR operator (a || b) is an infix operator made from two adjacent pipe characters. You use it to create logical expressions in which only one of the two values has to be true for the overall expression to be true.




Like the Logical AND operator above, the Logical OR operator uses short-circuit evaluation to consider its expressions. If the left side of a Logical OR expression is true, the right side is not evaluated, because it cannot change the outcome of the overall expression.




In the example below, the first Bool value (hasDoorKey) is false, but the second value (knowsOverridePassword) is true. Because one value is true, the overall expression also evaluates to true, and access is allowed:




let hasDoorKey = false


let knowsOverridePassword = true


if hasDoorKey || knowsOverridePassword {


print("Welcome!")


} else {


print("ACCESS DENIED")


}




// Prints "Welcome!"

Combining Logical Operators


&& ||

You can combine multiple logical operators to create longer compound expressions:




if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {


print("Welcome!")


} else {


print("ACCESS DENIED")


}




// Prints "Welcome!"




This example uses multiple && and || operators to create a longer compound expression. However, the && and || operators still operate on only two values, so this is actually three smaller expressions chained together. The example can be read as:




If we’ve entered the correct door code and passed the retina scan, or if we have a valid door key, or if we know the emergency override password, then allow access.




***NOTE*** The Swift logical operators && and || are left-associative, meaning that compound expressions with multiple logical operators evaluate the leftmost subexpression first.

(Explicit Parentheses)

It is sometimes useful to include parentheses when they are not strictly needed, to make the intention of a complex expression easier to read.




In the door access example, it is useful to add parentheses around the first part of the compound expression to make its intent explicit:




if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {


print("Welcome!")


} else {


print("ACCESS DENIED")


}




// Prints "Welcome!"




The parentheses make it clear that the first two values are considered as part of a separate possible state in the overall logic. The output of the compound expression doesn’t change, but the overall intention is clearer to the reader. Readability is always preferred over brevity; use parentheses where they help to make your intentions clear.

Strings

A string is a series of characters, such as "hello, world" or "albatross". Swift strings are represented by the String type. The contents of a String can be accessed in various ways, including as a collection of Character values.

String Literals

You can include predefined String values within your code as string literals. A string literal is a fixed sequence of textual characters surrounded by a pair of double quotes ("").




Use a string literal as an initial value for a constant or variable:




let someString = "Some string literal value"




Note that Swift infers a type of String for the someString constant, because it is initialized with a string literal value.

Initializing an Empty String

To create an empty String value as the starting point for building a longer string, either assign an empty string literal to a variable, or initialize a new String instance with initializer syntax:




var emptyString = ""




// empty string literal



var anotherEmptyString = String()




// initializer syntax




// these two strings are both empty, and are equivalent to each other

Find out whether a String value is empty by checking its Boolean isEmpty property:

if emptyString.isEmpty {


print("Nothing to see here")


}




// Prints "Nothing to see here"

String Mutability

You indicate whether a particular String can be modified (or mutated) by assigning it to a variable (in which case it can be modified), or to a constant (in which case it cannot be modified):




var variableString = "Horse"


variableString += " and carriage"




// variableString is now "Horse and carriage"




let constantString = "Highlander"


constantString += " and another Highlander"




// this reports a compile-time error - a constant string cannot be modified

Strings Are Value Types

Swift’s String type is a value type. If you create a new String value, that String value is copied when it is passed to a function or method, or when it is assigned to a constant or variable. In each case, a new copy of the existing String value is created, and the new copy is passed or assigned, not the original version.




Swift’s copy-by-default String behavior ensures that when a function or method passes you a String value, it is clear that you own that exact String value, regardless of where it came from. You can be confident that the string you are passed will not be modified unless you modify it yourself.




Behind the scenes, Swift’s compiler optimizes string usage so that actual copying takes place only when absolutely necessary. This means you always get great performance when working with strings as value types.

Working with Characters

You can access the individual Character values for a String by iterating over its characters property with a for-in loop:




for character in "Dog!🐶".characters {


print(character)


}




// D


// o


// g


// !


// 🐶

Working with Character


(continued)

Alternatively, you can create a stand-alone Character constant or variable from a single-character string literal by providing a Character type annotation:




let exclamationMark: Character = "!"

Working with Character


(continued)

String values can be constructed by passing an array of Character values as an argument to its initializer:




let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]


let catString = String(catCharacters)


print(catString)




// Prints "Cat!🐱"

Concatenating


Strings and Characters

String values can be added together (or concatenated) with the addition operator (+) to create a new String value:




let string1 = "hello"


let string2 = " there"


var welcome = string1 + string2




// welcome now equals "hello there"




You can also append a String value to an existing String variable with the addition assignment operator (+=):




var instruction = "look over"


instruction += string2




// instruction now equals "look over there"




You can append a Character value to a String variable with the String type’s append() method:




let exclamationMark: Character = "!"


welcome.append(exclamationMark)




// welcome now equals "hello there!"




***NOTE*** You can’t append a String or Character to an existing Character variable, because a Character value must contain a single character only.

String


Interpolation


"\(xyz)"

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash:




let multiplier = 3


let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"




// message is "3 times 2.5 is 7.5"




***NOTE*** The expressions you write inside parentheses within an interpolated string cannot contain an unescaped backslash (\), a carriage return, or a line feed. However, they can contain other string literals.

What is the value of totalScore?




var totalScore = 0


totalScore = ++totalScore

1

What is the value of totalScore?




var totalScore = 10 - 20


++totalScore

-9

What is the value of gameOver?




let gameOver = !false

True

What is the value of totalScore?




var levelScore = 100


var totalScore = -levelScore

-100

What is the value of totalScore?




var totalScore = 10


--totalScore

9