Monday, January 19, 2015

Control Flow

If

if myFirstName == "Mark"{
    print("Hello, \(myFirstName). You are an admin.")
}
else {
    print("Welcome, guest!")
}

Ternary Conditional Operator

 
let isAdmin: Bool = myFirstName == "Mark" ? true : false
 

Switch

switch myFirstName {
    case "Mark":
    print("Hello, \(myFirstName). You are an admin.")
case "Mark", "Chase":
    print("Hello, \(myFirstName). You are a user.")
default:
    print("Welcome, guest!")
}

// Note: No "break" statement is necessary.

For In

let iterations = 5

for index in 1...iterations {
    print("This is iteration \(index)")
}

// Note: The for loop is kind of deprecated, replaced by the for in loop.
for var x = 0; x < iterations; ++x {
    print("This is iteration \(x)")
}
For more examples of for in loops see post on Collections

While

var x = 0

while x < 5 {
    print("This is iteration \(x)")
    x++
}

repeat {
    print("This is iteration \(x)")
    x++
} while x < 5
(Updated for Swift 2.2)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...