For Loop Swift Variable Assignment

Branch statements allow the program to execute certain parts of code depending on the value of one or more conditions. The values of the conditions specified in a branch statement control how the program branches and, therefore, what block of code is executed. Swift has three branch statements: an statement, a statement, and a statement.

Control flow in an statement or a statement can be changed by a statement and is discussed in Break Statement below.

If Statement

An statement is used for executing code based on the evaluation of one or more conditions.

There are two basic forms of an statement. In each form, the opening and closing braces are required.

The first form allows code to be executed only when a condition is true and has the following form:

  • ifcondition {
  • statements
  • }

The second form of an statement provides an additional else clause (introduced by the keyword) and is used for executing one part of code when the condition is true and another part of code when the same condition is false. When a single else clause is present, an statement has the following form:

  • ifcondition {
  • statements to execute if condition is true
  • } else {
  • statements to execute if condition is false
  • }

The else clause of an statement can contain another statement to test more than one condition. An statement chained together in this way has the following form:

  • ifcondition 1 {
  • statements to execute if condition 1 is true
  • } elseifcondition 2 {
  • statements to execute if condition 2 is true
  • } else {
  • statements to execute if both conditions are false
  • }

The value of any condition in an statement must be of type or a type bridged to . The condition can also be an optional binding declaration, as discussed in Optional Binding.

Guard Statement

A statement is used to transfer program control out of a scope if one or more conditions aren’t met.

A statement has the following form:

  • guardconditionelse {
  • statements
  • }

The value of any condition in a statement must be of type or a type bridged to . The condition can also be an optional binding declaration, as discussed in Optional Binding.

Any constants or variables assigned a value from an optional binding declaration in a statement condition can be used for the rest of the guard statement’s enclosing scope.

The clause of a statement is required, and must either call a function with the return type or transfer program control outside the guard statement’s enclosing scope using one of the following statements:

Control transfer statements are discussed in Control Transfer Statements below. For more information on functions with the return type, see Functions that Never Return.

Switch Statement

A statement allows certain blocks of code to be executed depending on the value of a control expression.

A statement has the following form:

  • switchcontrol expression {
  • casepattern 1:
  • statements
  • casepattern 2wherecondition:
  • statements
  • casepattern 3wherecondition,
  • pattern 4wherecondition:
  • statements
  • default:
  • statements
  • }

The control expression of the statement is evaluated and then compared with the patterns specified in each case. If a match is found, the program executes the statements listed within the scope of that case. The scope of each case can’t be empty. As a result, you must include at least one statement following the colon () of each case label. Use a single statement if you don’t intend to execute any code in the body of a matched case.

The values of expressions your code can branch on are very flexible. For instance, in addition to the values of scalar types, such as integers and characters, your code can branch on the values of any type, including floating-point numbers, strings, tuples, instances of custom classes, and optionals. The value of the control expression can even be matched to the value of a case in an enumeration and checked for inclusion in a specified range of values. For examples of how to use these various types of values in statements, see Switch in Control Flow.

A case can optionally contain a clause after each pattern. A where clause is introduced by the keyword followed by an expression, and is used to provide an additional condition before a pattern in a case is considered matched to the control expression. If a clause is present, the statements within the relevant case are executed only if the value of the control expression matches one of the patterns of the case and the expression of the clause evaluates to . For instance, a control expression matches the case in the example below only if it is a tuple that contains two elements of the same value, such as .

    As the above example shows, patterns in a case can also bind constants using the keyword (they can also bind variables using the keyword). These constants (or variables) can then be referenced in a corresponding clause and throughout the rest of the code within the scope of the case. If the case contains multiple patterns that match the control expression, all of the patterns must contain the same constant or variable bindings, and each bound variable or constant must have the same type in all of the case’s patterns.

    A statement can also include a default case, introduced by the keyword. The code within a default case is executed only if no other cases match the control expression. A statement can include only one default case, which must appear at the end of the statement.

    Although the actual execution order of pattern-matching operations, and in particular the evaluation order of patterns in cases, is unspecified, pattern matching in a statement behaves as if the evaluation is performed in source order—that is, the order in which they appear in source code. As a result, if multiple cases contain patterns that evaluate to the same value, and thus can match the value of the control expression, the program executes only the code within the first matching case in source order.

    Switch Statements Must Be Exhaustive

    In Swift, every possible value of the control expression’s type must match the value of at least one pattern of a case. When this simply isn’t feasible (for instance, when the control expression’s type is ), you can include a default case to satisfy the requirement.

    Execution Does Not Fall Through Cases Implicitly

    After the code within a matched case has finished executing, the program exits from the statement. Program execution does not continue or “fall through” to the next case or default case. That said, if you want execution to continue from one case to the next, explicitly include a statement, which simply consists of the keyword, in the case from which you want execution to continue. For more information about the statement, see Fallthrough Statement below.

    Variables in Swift are a fundamental and powerful language concept. Although they seem simple, they include a lot of functionality, and there are also some common pitfalls you will encounter when doing Swift programming. 

    In this short video tutorial from my course on creating iOS apps with Swift 3, I'll explain variables, constants, and optionals, with a special emphasis on the Swift type system. 

    Create an iOS App With Swift 3: Variables, Constants, and Optionals

    Variables in Swift 3

    Swift has some features that are very powerful and handy when it comes to variables. Let's start with a brand new playground. 

    As you can see, there already is a variable assignment on the screen, which was created by the template. It has the keyword in front of it, followed by a variable name and the assignment—here, . So far, so good. 

    What you don't see in this line of code is a type assignment. It's not necessary. Let's create a new variable called int and give it the value :

    Okay, now let us change the variable to be the value . Immediately, the compiler complains that you're trying to set a value of type to be of type . 

    How does it know about this?

    It is inferred. Despite the way it looks, Swift is a statically typed language, which means every variable has a type. But unlike most other languages, it can infer the type when it gets assigned a value during definition. For our case, this means since the variable was given a string, it automatically received the type .

    The same for the variable. This one we can set to because it is an integer. 

    Sometimes, you want to explicitly specify the type of variable. Of course, this is possible also. Let's create a variable , and set it to . 

    We already know that it will be initialized to an integer, despite the name. So when we try to set it to , this will fail. To make sure it will be a double nonetheless, we have to set it by using a colon after the variable name, followed by the type, in upper case, . 

    Constants in Swift 3

    Okay, now on to constants. Those are the ones to use if you don't want to change the value you initially set.

    The Swift compiler is very smart about that and warns you if you use a variable where you want a constant and vice versa. To define a constant, you will need the keyword instead of . In the code from before, if you change the variable to a constant, the compiler will warn you about the change you're trying to make in the next line by setting it to .

    A thing that was very funny when Swift first came out is the fact that it is fully Unicode compatible. This also means that variable names can be any character in Unicode—like if you want to set  to . It even supports using emojis to name your variables and functions.

    Optionals in Swift 3

    The final major feature regarding variables in Swift is optionals.

    Whenever you define a variable, you need to initialize it before you use it. If you don't, your program won't compile. Sometimes, however, your variable won't always have a value. For example, when you have a callback function that either returns the result of an operation or an error. 

    Null Pointers

    There has always been the concept of null pointers in programming. In Swift, those are named nil. Those are initialized variables with a special value of nothing. If you want to allow a nil value for a variable in Swift, you have to explicitly say so and the variable becomes an optional. For example:

    var myVariable : String? print(myVariable)

    An optional is defined by adding a question mark to the type. This immediately makes the print statement work, and it outputs . 

    Let's change my variable to be a double, and let's multiply it by 2. Although nil is allowed, you can't do much with it. This means we need a safeguard. Since nil checks are a very common problem in programming, the language designers of Swift have decided to give us a special way of dealing with it.

    You might have learnt that variable assignment in an statement is bad practice. For Swift, this is different. If you're doing , it will automatically unwrap the optional for you and make it available in the if block for you if it isn't nil. 

    So let's initialize the variable with a value. In the block, it will multiply it by 2 and print it. But if we try to do the same outside the block, it will of course fail. 

    If you absolutely know that a variable has a value and you don't want to wrap it in a conditional, you can also forcefully unwrap it by using an exclamation point. This will unwrap it if there is a value, but if there isn't, it will fail very hard with a runtime exception. So if you're working with optionals a lot, definitely remember this special statement. 

    Type Conversion

    A very important thing when it comes to working with static types is type conversion.

    Let's say you have a double and want an integer. In Swift, every type comes with an initializer, even booleans or integers. The default types also have initializers for compatible types, so we can use the initializer to convert our double. 

    To further elaborate on type casting, I need to introduce a new set of types, collections. I'm pretty sure you know what an array is, and of course they also are available in Swift. Let's create an array of integers:

    You might be used to putting anything that comes to mind in an array and also mixing types. But in Swift, arrays are also statically typed against their values. This means if you want to add a string to your array of integers, Swift doesn't know what to do.  will give an error message.

    So let's remove the string and add it in a separate line to the array. Now it shows the error message I wanted to show you.

    This error comes from the type of the array, since it is inferred to be an array of integers. We can explicitly set it to this type by using square brackets around the type of the content. This is the most concise method of defining the array. 

    You could also use the type array and use angle brackets to define the type. This might look more familiar to you if you come from another language. Of course, there are some cases where you actually want to allow mixed types in an array. In a minute, I'm going to show you another data type where you will store the JSON response of a web server, which might contain numbers, booleans, or strings.

    There is a special keyword in Swift that allows those types to be present, and it is called . This means this can be any type. Of course, the problem is that we're still in a statically typed language. Now the values are of type . If we want to add the first two integers together, it simply fails to do so because the type doesn't support the addition operator.

    This means we have to use type casting to convert them to the correct type. We can use the keyword to do so. And, of course, since it's not safe, we need to use the bang as well to force it, as there is no known conversion between and . If we do this, though, we have to be very careful with the actual types. If we cast the wrong element to be an integer, it will fail at runtime with an exception. 

    Now, there's one important thing missing. That is dictionaries. If you come from another language, you might know them as maps or hashes.

    They have keys that have values. If you want to define them explicitly, you will do similar to the array using square brackets but separate the key and value by a colon. 

    Defining a key and an value would be a very common use case when parsing JSON data from the web.

    Watch the Full Course

    In the full course, Create iOS Apps With Swift 3, you will get a comprehensive guide to using Swift 3 to create iOS apps.

    Whether you're new to iOS app development or are looking to make the switch from Objective-C, this course will get you started with Swift for app development. You'll learn about all the basic features of the language, from variables to classes. You'll also get an introduction to using Xcode for app development as you follow along and implement the course project: an interactive Fibonacci sequence viewer.

    0 thoughts on “For Loop Swift Variable Assignment”

      -->

    Leave a Comment

    Your email address will not be published. Required fields are marked *