Swift5.3 — 1.Basic(2)

Jay Han
5 min readJan 5, 2021

Contents

  1. Boolean
  2. Tuples
  3. Optionals
  4. Error Handling
  5. Assertions and Preconditions

1. Boolean

Swift has a basic Boolean type Bool which refers to be as logical, because they can only be true or false.

let orangeIsOrange = true
let appleIsOrange = false

You can work with conditional statements such as the if statement

if appleIsOrange {
print("It's true")
}else{
print("It's false")
}
// Prints "It's false"

Swift’s type safety prevents non-Boolean values from being substituted for Bool.

let i = 1
if i{
// This example will not compile, and will report an error
// Because constant i is not Bool type
}
if i == 1{
// This example will compile successfully
// Because i == 1 is true and it is inferred as type of Bool
}

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

// heightAndWeight is of type (Int, Double)
let heightAndWeight = (180, 70.2)

You can decompose a tuple’s contents into separate constants or variables

let (height, weight) = heightAndWeight
print("Height : \(height)") // prints "Height : 180"
print("Weight : \(weight)") // prints "Weight : 70.2"

If you only need a tuple’s value, ignore the other one with underscore(_)

let(justHeight,_) = heightAndWeight
print("Height : \(height)") // prints "Height : 180"

Alternatively, access the individual element values in a tuple using index.

print("Height : \(heightAndWeight.0)")  // prints "Height : 180"
print("Weight : \(heightAndWeight.1)") // prints "Weight : 70.2"

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

let heightAndWeight = (height: 180, weight: 70.2)
print("Height: \(heightAndWeight.height)") // prints "Height: 180"
print("Weight: \(heightAndWeight.weight)") // prints "Weight: 70.2"

Tuples are useful for simple groups of related values. They’re not suited to the creation of complex data structures. If your data structure is likely to be more complex, model it as a class or structure, rather than as a tuple.

3. Optionals

You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, or there isn’t a value at all.

When we try to convert String value to Int value, not every string can be converted into an integer. For example, the string “123” can be converted into the numeric value 123, but the string “hello, world” doesn’t have an obvious numeric value to convert to.

let stringNumber= "123"
let intNumber= Int(stringNumber)
// intNumber is inferred to be "Int?" or "optional Int" not "Int"

Because the initializer might fail, it returns an optional Int, rather than an Int. An optional Int is written as Int? (includes “?”), not Int. The question mark indicates that the value it contains is optional, meaning that it might contain Int or no value at all. Of course, it can’t contain anything else, such as Bool value or String value)

nil

You set an optional variable to a valueless state by assigning it the special value nil. You can’t use nil with non-optional constants and variables.

var weight: Double? = 70.2
// weight contains an actual Double value of 70.2
weight = nil
// weight now contains no value

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

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

You can check if the value is nil with if statement.

var message = "Hello"
if message != nil{
print("message contains some String value")
}
// Prints "message contains some String value"

Once you’re sure that the optional contains a value, you can access its value by adding exclamation point (!) to the end of the optional’s name. Exclamation point means that “I know that this optional definitely has a value; please use it.”

var message = "Hello"
if message != nil{
print("message contains String of \(message!)")
}
// Prints "message contains String of Hello"

Optional Binding

You can use optional binding to find out whether an optional contains a value.

// if possibleNumber can be converted to Int, the condition is trueif let actualNumber = Int(possibleNumber){
print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)")
}else{
print("The string \"\(possibleNumber)\" could not be converted to an integer)
}
// Prints "The string "123 has an integer value of 123"

Multiple bindings

if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100{
print("\(firstNumber) < \(secondNumber) < 100)
}
// Prints "4 < 42 < 100"

Implicitly Unwrapped Optionals

Sometimes 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, because it can be safely assumed to have a value all of the time.

let possibleString: String? = "An optional string."
let forcedString: String = possibleString!
// requires an exclamation point
let assumedString: String! = "An implicitly unwrapped optional String"
let implicitString: String = assumedString
// no need for an exclamation point

4. Error Handling

Error handling allows you to determine the underlying cause of failure, and, if necessary, propagate the error to another part of your program.

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

// Create a function
func makeASandwich() throw {
// this function may or may not throw an error
}
do{
try makeASandwich()
// no error was thrown
eatASandwich
}catch SandwichError.outOfCleanDishes{
// an error was thrown
washDishese()
}catch SanwichError.missingIngredients(let ingredients){
buyGroceries(ingredients)
}

5. Assertions and Preconditions

Assertions and preconditions are checks that happen at runtime. Assertions are checked only in debug builds, but preconditions are checked both debug and production builds.

let age = -3
assert(age >= 0, "A person's age can't be less than zero.")
// This assertion fails because -3 is not >= 0
assert(age >= 0)
// You can omit message

If the code already checks the condition, you use the assertionFailure function to indicate that an assertion has failed.

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

You can do same work with precondition, preconditionFailure.

let age = -3
precondition(age >= 0, "A person's age can't be less than zero.")
// This assertion fails because -3 is not >= 0
precondition(age >= 0)
// You can omit message
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 {
preconditionFailure("A person's age can't be less than zero.")
}

--

--