Going from Swift to Go: Basic Flow Control

Going from Swift to Go: Basic Flow Control

Time for some basic flow control. In this post, we will look at if statements, switch blocks, and for loops in Swift and Go.

If Statements

In both Swift and Go, if statements have the same format: if something { execute } else { do something else }, where the else statement is optional. Example:

if 3 > 2 {
//do something
} else {
//this should not execute
}

Switch Blocks

In both Swift and go, the switch statement starts with ‘switch’ followed by the switch variable and brackets. In the brackets, we list out the cases. In both languages, if something executes in a case, we do not write break; however, if nothing executes in Swift, we must write ‘break’ (in Go we can leave the case blank). Additionally, while a ‘default’ case is mandatory in Swift, it is optional in Go.

Swift Example:

let x = 4
switch x {
case 1:
break
case 4:
print("success")
default:
break
}

Go Example:

x := 4
switch x {
case 1:
case 4:
fmt.Println("success")
}

For Loops

Go uses the traditional f0r loop format of (define variable, loop termination condition, loop iteration). However, Swift cannot use this format; instead, the we use ‘for’ followed by the variable declaration, followed by a list of numbers separated by …, ..<, or ..> , which indicate a range of values through which we iterate.

Go example:

for x := 0; x < 4; x-- {
//Do something
}

Swift example:

for x in 0..<4 {
//do something
}

For Loops with List

In both Swift and Go, a for loop can iterate through a list of objects. In Swift we accomplish this by creating the list, such as an array, and saying ‘for variableName in (our array). In Go, a for loop that iterates through a list is set up to iterate through a dictionary. Thus, if we have a dictionary, we can say ‘for keyName, valueName := range ourDictionary’ and iterate as such. If, however, we have an array or splice that we wish to iterate through, we must replace ‘keyName’ with ‘_’.

Swift example

for myWord in ["start", "middle", "end"] {
print(myWord)
}

Go example with dictionary

for myKey, myWord := range map[int]string{1: "start", 2: "middle", 3: "end"} {
fmt.print{"%d, %s", myKey, myWord}
}

Go example with array

for _, myWord := range []string{"start", "middle", "end"} {
fmt.print{"%s", myWord}
}