Swift Guard Statement – Why you should use it

https://stackoverflow.com/a/35046681/3151712For-In Loops

You use the for-in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string.

let names = [“Anna”, “Alex”, “Brian”, “Jack”]
for name in names {
   print(“Hello, (name)!”)
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!

You can also iterate over a dictionary to access its key-value pairs. Each item in the dictionary is returned as a (key, value) tuple when the dictionary is iterated, and you can decompose the (key, value) tuple’s members as explicitly named constants for use within the body of the for-in loop. In the code example below, the dictionary’s keys are decomposed into a constant called animalName, and the dictionary’s values are decomposed into a constant called legCount.

let numberOfLegs = [“spider”: 8, “ant”: 6, “cat”: 4]
for (animalName, legCount) in numberOfLegs {
   print(“(animalName)s have (legCount) legs”)
// ants have 6 legs
// spiders have 8 legs
// cats have 4 legs

for index in 1…5 {
   print(“(index) times 5 is (index * 5)”)
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

If you don’t need each value from a sequence, you can ignore the values by using an underscore in place of a variable name.

let base = 3
let power = 10
var answer = 1
for _ in 1…power {
   answer *= base
print(“(base) to the power of (power) is (answer)”)
// Prints “3 to the power of 10 is 59049”

let minutes = 60
for tickMark in 0..<minutes {
   // render the tick mark each minute (60 times)

stride(from:to:by:) function

let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
   // render the tick mark every 5 minutes (0, 5, 10, 15 … 45, 50, 55)

Closed ranges are also available, by using stride(from:through:by:) instead:

let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
   // render the tick mark every 3 hours (3, 6, 9, 12)

While Loops

  • while evaluates its condition at the start of each pass through the loop.
  • repeat-while evaluates its condition at the end of each pass through the loop.


A while loop starts by evaluating a single condition. If the condition is true, a set of statements is repeated until the condition becomes false.

while square < finalSquare {
   // roll the dice


The other variation of the while loop, known as the repeat-while loop, performs a single pass through the loop block first, before considering the loop’s condition. It then continues to repeat the loop until the condition is false.

repeat {
   // move up or down for a snake or ladder
} while square < finalSquare

Conditional Statements


if temperatureInFahrenheit <= 32 {
   print(“It’s very cold. Consider wearing a scarf.”)
} else if temperatureInFahrenheit >= 86 {
   print(“It’s really warm. Don’t forget to wear sunscreen.”)
} else {
   print(“It’s not that cold. Wear a t-shirt.”)
// Prints “It’s really warm. Don’t forget to wear sunscreen.”


let someCharacter: Character = “z”
switch someCharacter {
case “a”:
   print(“The first letter of the alphabet”)
case “z”:
   print(“The last letter of the alphabet”)
   print(“Some other character”)
// Prints “The last letter of the alphabet”

No Implicit Fallthrough

In contrast with switch statements in C and Objective-C, switch statements in Swift do not fall through the bottom of each case and into the next one by default. Instead, the entire switch statement finishes its execution as soon as the first matching switch case is completed, without requiring an explicit breakstatement.


Although break is not required in Swift, you can use a break statement to match and ignore a particular case or to break out of a matched case before that case has completed its execution.

The body of each case must contain at least one executable statement. It is not valid to write the following code, because the first case is empty:

let anotherCharacter: Character = “a”
switch anotherCharacter {
case “a”: // Invalid, the case has an empty body
case “A”:
   print(“The letter A”)
   print(“Not the letter A”)
// This will report a compile-time error.

To make a switch with a single case that matches both "a" and "A", combine the two values into a compound case, separating the values with commas.

let anotherCharacter: Character = “a”
switch anotherCharacter {
case “a”, “A”:
   print(“The letter A”)
   print(“Not the letter A”)
// Prints “The letter A”

Interval Matching

let approximateCount = 62
let countedThings = “moons orbiting Saturn”
let naturalCount: String
switch approximateCount {
case 0:
   naturalCount = “no”
case 1..<5:
   naturalCount = “a few”
case 5..<12:
   naturalCount = “several”
case 12..<100:
   naturalCount = “dozens of”
case 100..<1000:
   naturalCount = “hundreds of”
   naturalCount = “many”
print(“There are (naturalCount) (countedThings).”)
// Prints “There are dozens of moons orbiting Saturn.”


You can use tuples to test multiple values in the same switch statement. use the underscore character (_), also known as the wildcard pattern, to match any possible value.

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
   print(“(somePoint) is at the origin”)
case (_, 0):
   print(“(somePoint) is on the x-axis”)
case (0, _):
   print(“(somePoint) is on the y-axis”)
case (-2…2, -2…2):
   print(“(somePoint) is inside the box”)
   print(“(somePoint) is outside of the box”)
// Prints “(1, 1) is inside the box”

n fact, the point (0, 0) could match all four of the cases in this example. However, if multiple matches are possible, the first matching case is always used. The point (0, 0) would match case (0, 0) first, and so all other matching cases would be ignored.

Value Bindings

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
   print(“on the x-axis with an x value of (x)”)
case (0, let y):
   print(“on the y-axis with a y value of (y)”)
case let (x, y):
   print(“somewhere else at ((x), (y))”)
// Prints “on the x-axis with an x value of 2”

After the temporary constants are declared, they can be used within the case’s code block. 

This switch statement does not have a default case. The final case, case let (x, y), declares a tuple of two placeholder constants that can match any value. Because anotherPoint is always a tuple of two values, this case matches all possible remaining values, and a default case is not needed to make the switch statement exhaustive.


A switch case can use a where clause to check for additional conditions.

let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
   print(“((x), (y)) is on the line x == y”)
case let (x, y) where x == -y:
   print(“((x), (y)) is on the line x == -y”)
case let (x, y):
   print(“((x), (y)) is just some arbitrary point”)
// Prints “(1, -1) is on the line x == -y”

Compound Cases

Multiple switch cases that share the same body can be combined by writing several patterns after case, with a comma between each of the patterns.

let someCharacter: Character = “e”
switch someCharacter {
case “a”, “e”, “i”, “o”, “u”:
   print(“(someCharacter) is a vowel”)
case “b”, “c”, “d”, “f”, “g”, “h”, “j”, “k”, “l”, “m”,
    “n”, “p”, “q”, “r”, “s”, “t”, “v”, “w”, “x”, “y”, “z”:
   print(“(someCharacter) is a consonant”)
   print(“(someCharacter) is not a vowel or a consonant”)
// Prints “e is a vowel”

let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
   print(“On an axis, (distance) from the origin”)
   print(“Not on an axis”)
// Prints “On an axis, 9 from the origin”

Control Transfer Statements

  • continue
  • break
  • fallthrough
  • return
  • throw


The continue statement tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop.

let puzzleInput = “great minds think alike”
var puzzleOutput = “”
let charactersToRemove: [Character] = [“a”, “e”, “i”, “o”, “u”, “ ”]
for character in puzzleInput {
   if charactersToRemove.contains(character) {
   } else {
// Prints “grtmndsthnklk”


The break statement ends execution of an entire control flow statement immediately. The break statement can be used inside a switch or loop statement when you want to terminate the execution of the switch or loop statement earlier than would otherwise be the case.

Break in a Loop Statement

When used inside a loop statement, break ends the loop’s execution immediately and transfers control to the code after the loop’s closing brace (}). No further code from the current iteration of the loop is executed, and no further iterations of the loop are started.

Break in a Switch Statement

When used inside a switch statement, break causes the switch statement to end its execution immediately and to transfer control to the code after the switch statement’s closing brace (}).


In Swift,the entire switch statement completes its execution as soon as the first matching case is completed. By contrast, C requires you to insert an explicit break statement at the end of every switch case to prevent fallthrough

let integerToDescribe = 5
var description = “The number (integerToDescribe) is”
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
   description += “ a prime number, and also”
   description += “ an integer.”
// Prints “The number 5 is a prime number, and also an integer.”


The fallthrough keyword simply causes code execution to move directly to the statements inside the next case (or default case) block, as in C’s standard switch statement behavior.

Labeled Statements

gameLoop: while square != finalSquare {
   diceRoll += 1
   if diceRoll == 7 { diceRoll = 1 }
   switch square + diceRoll {
   case finalSquare:
       // diceRoll will move us to the final square, so the game is over
       break gameLoop
   case let newSquare where newSquare > finalSquare:
       // diceRoll will move us beyond the final square, so roll again
       continue gameLoop
       // this is a valid move, so find out its effect
       square += diceRoll
       square += board[square]
print(“Game over!”)

Early Exit

A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition is not true.

func greet(person: [String: String]) {
   guard let name = person[“name”] else {
   print(“Hello (name)!”)
   guard let location = person[“location”] else {
       print(“I hope the weather is nice near you.”)
   print(“I hope the weather is nice in (location).”)
greet(person: [“name”: “John”])
// Prints “Hello John!”
// Prints “I hope the weather is nice near you.”
greet(person: [“name”: “Jane”, “location”: “Cupertino”])
// Prints “Hello Jane!”
// Prints “I hope the weather is nice in Cupertino.”

If the guard statement’s condition is met, code execution continues after the guard statement’s closing brace. Any variables or constants that were assigned values using an optional binding as part of the condition are available for the rest of the code block that the guard statement appears in.

If that condition is not met, the code inside the else branch is executed. That branch must transfer control to exit the code block in which the guard statement appears. It can do this with a control transfer statement such as return, break, continue, or throw, or it can call a function or method that doesn’t return, such as fatalError(_:file:line:).


ref) https://ericcerney.com/swift-guard-statement/

optional binding ref) https://stackoverflow.com/a/35046681/3151712

Checking API Availability

Swift has built-in support for checking API availability, which ensures that you don’t accidentally use APIs that are unavailable on a given deployment target.

You use an availability condition in an if or guard statement to conditionally execute a block of code.

if #available(iOS 10, macOS 10.12, *) {
   // Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
} else {
   // Fall back to earlier iOS and macOS APIs

if #available(platform name version, …, *) {
   statements to execute if the APIs are available
} else {
   fallback statements to execute if the APIs are unavailable

Assignment Operator

let b = 10
var a = 5
a = b
// a is now equal to 10

let (x, y) = (1, 2)
// x is equal to 1, and y is equal to 2

the assignment operator in Swift does not itself return a value. The following statement is not valid.

if x = y {
   // This is not valid, because x = y does not return a value.

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 Swift arithmetic operators don’t allow values to overflow by default. You can opt in to value overflow behavior by using Swift’s overflow operators (such as a &+ b)

The addition operator is also supported for String concatenation:

“hello, ” + “world”  // equals “hello, world”

Remainder Operator

The remainder operator (a % b)

9 % 4    // equals 1

-9 % 4   // equals -1

The sign of b is ignored for negative values of b. This means that a % b and a % -b always give the same answer.

Unary Minus Operator

let three = 3
let minusThree = -three       // minusThree equals -3
let plusThree = -minusThree   // plusThree equals 3, or “minus minus three”

Unary Plus Operator

let minusSix = -6
let alsoMinusSix = +minusSix  // alsoMinusSix equals -6

the unary plus operator doesn’t actually do anything.

Compound Assignment Operators

var a = 1
a += 2
// a is now equal to 3


The compound assignment operators don’t return a value. For example, you can’t write let b = a += 2.

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)


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

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

You can compare two tuples if they have the same type and the same number of values. Tuples are compared from left to right, one value at a time, until the comparison finds two values that aren’t equal.

(1, “zebra”) < (2, “apple”)   // true because 1 is less than 2; “zebra” and “apple” are not compared
(3, “apple”) < (3, “bird”)    // true because 3 is equal to 3, and “apple” is less than “bird”
(4, “dog”) == (4, “dog”)      // true because 4 is equal to 4, and “dog” is equal to “dog”

In the example above, you can see the left-to-right comparison behavior on the first line. Because 1 is less than 2, (1, "zebra") is considered less than (2, "apple"), regardless of any other values in the tuples. It doesn’t matter that "zebra" isn’t less than "apple", because the comparison is already determined by the tuples’ first elements. However, when the tuples’ first elements are the same, their second elements arecompared—this is what happens on the second and third line.

Tuples can be compared with a given operator only if the operator can be applied to each value in the respective tuples. For example, as demonstrated in the code below, you can compare two tuples of type (String, Int) because both String and Int values can be compared using the < operator. In contrast, two tuples of type (String, Bool) can’t be compared with the < operator because the < operator can’t be applied to Bool values.

(“blue”, -1) < (“purple”, 1)        // OK, evaluates to true
(“blue”, false) < (“purple”, true)  // Error because < can’t compare Boolean values


The Swift standard library includes tuple comparison operators for tuples with fewer than seven elements. To compare tuples with seven or more elements, you must implement the comparison operators yourself.

Ternary Conditional Operator

question ? answer1 : answer2

와 아래는 같은내용

if question {
} else {

Nil-Coalescing Operator

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

a ?? b  는 아래돠 같은 내용

a != nil ? a! : b


If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.

Range Operators

closed range operator

a...b defines a range that runs from a to b, and includes the values a and b

for index in 1…5 {
   print(“(index) times 5 is (index * 5)”)
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

Half-Open Range Operator

a..<b defines a range that runs from a to b, but doesn’t include b

Half-open ranges are particularly useful when you work with zero-based lists such as arrays. 

let names = [“Anna”, “Alex”, “Brian”, “Jack”]
let count = names.count
for i in 0..<count {
   print(“Person (i + 1) is called (names[i])”)
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

One-Sided Ranges

for name in names[2…] {
// Brian
// Jack

for name in names[…2] {
// Anna
// Alex
// Brian

for name in names[..<2] {
// Anna
// Alex

let range = …5
range.contains(7)   // false
range.contains(4)   // true
range.contains(-1)  // true

Logical Operators

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

Logical AND Operator

let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
} else {
   print(“ACCESS DENIED”)

Logical OR Operator

let hasDoorKey = false
let knowsOverridePassword = true
if hasDoorKey || knowsOverridePassword {
} else {
   print(“ACCESS DENIED”)
// Prints “Welcome!”


Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. An 8-bit unsigned integer is of type UInt8.

let minValue = UInt8.min  // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max  // maxValue is equal to 255, and is of type UInt8

Swift provides integer type, Int, which has the same size as the current platform’s native word size

On a 32-bit platform, Int is the same size as Int32.

On a 64-bit platform, Int is the same size as Int64.

On a 32-bit platform, UInt is the same size as UInt32.

On a 64-bit platform, UInt is the same size as UInt64.

Floating-Point Numbers

  • Double represents a 64-bit floating-point number.
  • Float represents a 32-bit floating-point number.

Type Safety and Type Inference

swift는 Type Safe 언어이다. 즉 Int로 정해진 변수에 Double타입의 데이터를 대입할수 없다. 그렇다고 모든 상수,변수의 data type을 정해줘야하는 것은 아니다. 처음 대입하는 데이터를 가지고 swift는 알맞은 data type을 정한다. 이를 type inference라고 한다.

Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers.

Numeric Literals

let decimalInteger = 17
let binaryInteger = 0b10001       // 17 in binary notation
let octalInteger = 0o21           // 17 in octal notation
let hexadecimalInteger = 0x11     // 17 in hexadecimal notation

  • 1.25e2 means 1.25 x 102, or 125.0.
  • 1.25e-2 means 1.25 x 10-2, or 0.0125.

let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1

Numeric Type Conversion

let cannotBeNegative: UInt8 = -1
// UInt8 cannot store negative numbers, and so this will report an error

let tooBig: Int8 = Int8.max + 1
// Int8 cannot store a number larger than its maximum value,
// and so this will also report an error

let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to be of type Double


The rules for combining numeric constants and variables are different from the rules for numeric literals. The literal value 3 can be added directly to the literal value 0.14159, because number literals don’t have an explicit type in and of themselves. Their type is inferred only at the point that they’re evaluated by the compiler. 그냥 literal 끼리 변수,상수에 할당하기 전에 연산하는 것은 가능하다는 이야기 이다. 

Type Aliases

typealias AudioSample = UInt16

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


let orangesAreOrange = true
let turnipsAreDelicious = false

let i = 1
if i {
  // this example will not compile, and will report an error, 일반 다른타입의 데이터는 Bool



The values within a tuple can be of any type and don’t have to be of the same type as each other.

let http404Error = (404, “Not Found”)
let (statusCode, statusMessage) = http404Error

print(“The status code is (statusCode)”)
// Prints “The status code is 404”

print(“The status message is (statusMessage)”)
// Prints “The status message is Not Found”

If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (_) when you decompose the tuple:

let (justTheStatusCode, _) = http404Error

print(“The status code is (justTheStatusCode)”)
// Prints “The status code is 404”

Alternatively, access the individual element values in a tuple using index numbers starting at zero:

print(“The status code is (http404Error.0)”)
// Prints “The status code is 404”

print(“The status message is (http404Error.1)”)
// Prints “The status message is Not Found”

You can name the individual elements in a tuple when the tuple is defined:

let http200Status = (statusCode: 200, description: “OK”)

If you name the elements in a tuple, you can use the element names to access the values of those elements:

print(“The status code is (http200Status.statusCode)”)
// Prints “The status code is 200”

print(“The status message is (http200Status.description)”)
// Prints “The status message is OK”


You use optionals in situations where a value may be absent.

let possibleNumber = “123”
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type “Int?”, or “optional Int”

위에서 possibleNumber가 다른 일반 string의 경우에는 Int전환이 불가능하다. 그런 경우는 convertedNumber 에 nil 이 저장될수 있으므로 convertedNumber 는 Int?로 자동 설정되는 것이다.

var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404

serverResponseCode = nil
// serverResponseCode now contains no value


You can’t use nil with nonoptional constants and variables. If a constant or variable in your code needs to work with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type.

If you define an optional variable without providing a default value, the variable is automatically set to nil for you:

var surveyAnswer: String?
// surveyAnswer is automatically set to nil

If Statements and Forced Unwrapping

You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=).

Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. 

if convertedNumber != nil {
   print(“convertedNumber has an integer value of (convertedNumber!).”)
// Prints “convertedNumber has an integer value of 123.”


Trying to use ! to access a nonexistent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

Optional Binding

You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.

if let actualNumber = Int(possibleNumber) {
   print(“”(possibleNumber)” has an integer value of (actualNumber)”)
} else {
   print(“”(possibleNumber)” could not be converted to an integer”)
// Prints “"123” has an integer value of 123"

You can include as many optional bindings and Boolean conditions in a single if statement as you need to, separated by commas. If any of the values in the optional bindings are nil or any Boolean condition evaluates to false, the whole if statement’s condition is considered to be false. (여러개의 optional binding을 하나의 if 구문에서 사용하는 것은 여러개의 조건문이 and로 연결된것으로 본다)

if let firstNumber = Int(“4”), let secondNumber = Int(“42”), firstNumber < secondNumber && secondNumber < 100 {
   print(“(firstNumber) < (secondNumber) < 100”)
// Prints “4 < 42 < 100”

implicitly Unwrapped Optionals

it’s clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it’s useful to remove the need to check and unwrap the optional’s value every time it’s accessed.

You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type.

let possibleString: String? = “An optional string.”
let forcedString: String = possibleString! // requires an exclamation mark

let assumedString: String! = “An implicitly unwrapped optional string.”
let implicitString: String = assumedString // no need for an exclamation mark

You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:

if assumedString != nil {
// Prints “An implicitly unwrapped optional string.”

You can also use an implicitly unwrapped optional with optional binding, to check and unwrap its value in a single statement:

if let definiteString = assumedString {
// Prints “An implicitly unwrapped optional string.”


Don’t use an implicitly unwrapped optional when there’s a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.

Error Handling

When a function encounters an error condition, it throws an error. That function’s caller can then catch the error and respond appropriately.

func canThrowAnError() throws {
   // this function may or may not throw an error

A function indicates that it can throw an error by including the throws keyword in its declaration. When you call a function that can throw an error, you prepend the try keyword to the expression.

Swift automatically propagates errors out of their current scope until they’re handled by a catch clause.

do {
   try canThrowAnError()
   // no error was thrown
} catch {
   // an error was thrown

A do statement creates a new containing scope, which allows errors to be propagated to one or more catchclauses.

Here’s an example of how error handling can be used to respond to different error conditions:

func makeASandwich() throws {
   // …

do {
   try makeASandwich()
} catch SandwichError.outOfCleanDishes {
} catch SandwichError.missingIngredients(let ingredients) {


Assertions and Preconditions

You use them to make sure an essential condition is satisfied before executing any further code. If the Boolean condition in the assertion or precondition evaluates to true, code execution continues as usual. If the condition evaluates to false, the current state of the program is invalid; code execution ends, and your app is terminated.

error handling과는 달리 assertions and preconditions aren’t used for recoverable or expected errors. (통과하지 못하면 프로그램 정지)

The difference between assertions and preconditions is in when they’re checked: Assertions are checked only in debug builds, but preconditions are checked in both debug and production builds.

Debugging with Assertions

let age = -3
assert(age >= 0, “A person’s age can’t be less than zero.”)
// This assertion fails because -3 is not >= 0.

You can omit the assertion message

assert(age >= 0)

If the code already checks the condition, you use the assertionFailure(_:file:line:) function to indicate that an assertion has failed. For example:

if age > 10 {
   print(“You can ride the roller-coaster or the ferris wheel.”)
} else if age > 0 {
   print(“You can ride the ferris wheel.”)
} else {
   assertionFailure(“A person’s age can’t be less than zero.”)

Enforcing Preconditions

// In the implementation of a subscript…
precondition(index > 0, “Index must be greater than zero.”)

Multiple APK Support | Android Developers

AlertDialog 를 이용하는 방법과 PopupMenu를 이용하는 방법이 있다.

AlertDialog를 이용하는 경우

PopupMenu를 이용하는 경우