Posts

Showing posts from October, 2023

Swift: String literals, String mutability

String Literals String literals in Swift are sequences of characters enclosed in double quotation marks ("). They can be used to represent text, code, or other types of data. String literals can be created in a variety of ways. The most common way is to simply type the string between double quotation marks. For example, the following code snippet creates a string literal: let myStringLiteral = "Hello, world!" String literals can also be created using escape sequences. Escape sequences are used to represent special characters, such as newlines and tabs. For example, the following code snippet creates a string literal that contains a newline character: let myStringLiteral = "This is a string literal that contains a newline character: \n" String literals can also be created using multiline strings. Multiline strings are sequences of characters enclosed in three double quotation marks ("""). They can be used to represent text that spans mult

Swift: Logical Operators, Combining Logical Operators

Logical operators  Logical operators in Swift are used to combine two Boolean expressions and produce a single Boolean result. The three most common logical operators in Swift are: Logical AND (&&): The logical AND operator returns true only if both of its operands are true . Otherwise, it returns false . Logical OR (||): The logical OR operator returns true if either of its operands is true . Otherwise, it returns false . Logical NOT (!): The logical NOT operator reverses the truth value of its operand. If the operand is true , the logical NOT operator returns false . Otherwise, it returns true . Logical operators can be used to implement a variety of logic in Swift code, such as conditional statements, loops, and guard statements. For example, the following code snippet uses the logical AND operator to check if a number is both even and greater than 10: let number = 12  if number % 2 == 0 && number > 10 {   print("The number is even and greater than 10.&qu

Swift: Range Operators - Closed Range Operator, Half-Open Range Operator, One-Sided Ranges

Range operators Range operators in Swift provide a concise way to express a sequence of values. They are commonly used to iterate through a range of numbers, characters, or other elements. Swift offers two primary range operators: Closed Range Operator (...): The closed range operator, denoted by three dots (...), creates a range that includes both the starting and ending values. For instance, the range 1...5 encompasses the numbers 1, 2, 3, 4, and 5. Half-Open Range Operator  (..<): The half-open range operator, denoted by two dots followed by a less-than sign (..<), creates a range that includes the starting value but excludes the ending value. For example, the range 1..<5 includes the numbers 1, 2, 3, and 4, but not 5. Range operators can be used in various contexts, including: For-in loops: Range operators are frequently employed in for-in loops to iterate through a sequence of values. For instance, to print all numbers from 1 to 5, you can use a for-in loop with a

Swift: Operators: Comparison Operators, Ternary Conditional Operator, Nil-Coalescing Operator

Comparison operators Comparison operators compare two values and return a Boolean value indicating whether the relationship between the two values is true or false. The following table shows the most common comparison operators in Swift: Operator Description == Equal to != Not Equal to < Less Than > Greater Than <= Less than or equal to >= Greater than or equal to Comparison operators can be used on any type of value, including integers, floating-point numbers, booleans, and strings. Here are some examples of how to use comparison operators: // Check if two integers are equal  let number1: Int = 10  let number2: Int = 10 if number1 == number2 {   print("number1 is equal to number2.")  } else {   print("number1 is not equal to number2.")  } // Check if two floating-point numbers are equal  let decimal1: Double = 3.14  let decimal2: Double = 3.14 if decimal1 == decimal2 {   print("decimal1 is equa

Swift: Operators: Unary Plus Operator, Compound Assignment Operators

Unary Plus Operator The unary plus operator ( + ) is a prefix operator, which means that it is placed before the operand it operates on. It is used to force a value to be positive. This is useful for values that may be negative or zero. The unary plus operator can be used on any type of numeric value, including integers, floating-point numbers, and booleans. It can also be used on the result of an expression. Here are some examples of how to use the unary plus operator: // Force the value of an integer variable to be positive  var number: Int = -10  number = +number // number is now equal to 10  // Force the value of a floating-point variable to be positive  var decimal: Double = -3.14  decimal = +decimal // decimal is now equal to 3.14  // Force the value of a boolean variable to be positive  var isTrue: Bool = false  isTrue = +isTrue // isTrue is now equal to true  // Force the result of an expression to be positive  let difference = 10 - 5  let positiveDifference = +differen

Swift: Operators - Assignment, Arithmetic, Remainder, Unary Minus

Basic Operators Operators are symbols that perform operations on values. For example, the + operator performs the addition operation. The * operator performs the multiplication operation. There are many different types of operators in Swift, including: Arithmetic operators : Arithmetic operators perform mathematical operations on values, such as addition, subtraction, multiplication, and division. Comparison operators : Comparison operators compare two values and return a Boolean value indicating whether the relationship between the two values is true or false. Logical operators : Logical operators combine two or more Boolean values and return a single Boolean value. Bitwise operators : Bitwise operators perform operations on the individual bits of a value. Compound assignment operators : Compound assignment operators combine an assignment operation with an arithmetic or bitwise operation. Terminology The following are some important terms to know when discussing operators: Ope

Swift: Error Handling, Assertions and Preconditions, Debugging with Assertions, Enforcing Preconditions

Error Handling Error handling in Swift is a powerful and flexible system that allows you to catch and handle errors that occur during the execution of your program. Errors can occur for a variety of reasons, such as invalid user input, network problems, or hardware failures. There are two main ways to handle errors in Swift: Try-catch statements : Try-catch statements allow you to wrap a block of code in a try block and then provide a catch block to handle any errors that occur in the try block. If an error occurs, the catch block will be executed and the error can be handled. Do-throw statements : Do-throw statements allow you to throw errors from your code. This can be useful for indicating that an error has occurred and that the program cannot continue. In addition to try-catch statements and do-throw statements, Swift also provides a number of other features for error handling, such as: Error types : Error types can be used to represent different types of errors. This can be useful

Swift: Providing a Fallback Value, Force Unwrapping, Implicitly Unwrapped Optionals

Providing a Fallback Value If you need to use the value of an optional variable, but you are not sure if it has a value, you can provide a fallback value. This is a value that will be used if the optional variable is nil . To provide a fallback value, you can use the nil coalescing operator ( ?? ).  The syntax is as follows: optionalVariable ?? fallbackValue If the optional variable has a value, the value of the optional variable will be returned. If the optional variable is nil , the fallback value will be returned. For example, the following code uses the nil coalescing operator to provide a fallback value for the optionalInt variable: var optionalInt: Int? let value = optionalInt ?? 10 print("The value of the optionalInt variable is \(value).") In this example, if the optionalInt variable has a value, the value of the variable will be printed to the console. If the optionalInt variable is nil , the value 10 will be printed to the console. Force Unwrapping Force u

Swift: Optionals, nil, Optional Binding

Optionals Optionals are a way to represent a value that may or may not exist. They are useful for handling situations where a value may be missing or unknown. To declare an optional, use the ? symbol after the type name. For example, the following code declares an optional Int variable: var optionalInt: Int? The optional Int variable can be either nil or a valid Int value. nil The nil value is a special value that represents the absence of a value. It is used to indicate that an optional variable does not have a value. Example: var optionalInt: Int? optionalInt = nil Optional Binding Optional binding is a way to safely access the value of an optional variable. It can be used to avoid errors that can occur when trying to access the value of an optional variable that is nil . To use optional binding, use the if let statement. The syntax is as follows: if let value = optionalVariable {   // The optional variable has a value. } else {   // The optional variable is nil. } For exa

Swift: Type Aliases, Booleans, Tuples

Type Aliases Type aliases are a way to give a new name to an existing type. This can be useful for making your code more readable and understandable. To create a type alias, use the typealias keyword. The syntax is as follows: typealias NewTypeName = ExistingTypeName For example, the following code creates a type alias called Distance for the Double type: typealias Distance = Double Once you have created a type alias, you can use it anywhere you would use the existing type. For example, the following code declares a variable of type Distance : var distance: Distance = 10.0 Booleans Booleans are a special type of value that can be either true or false . Booleans are often used in conditional statements, such as if and while statements. For example, the following code uses a boolean to control the flow of the program: let isLoggedIn = true if isLoggedIn {   // The user is logged in. } else {   // The user is not logged in. } Tuples Tuples are a way to group together values of di