DEV Community

Cover image for Swift Quiz #03 — Basic Operators in Swift
Quizzesforyou
Quizzesforyou

Posted on • Edited on • Originally published at Medium

Swift Quiz #03 — Basic Operators in Swift

Checkout the interactive quiz of this story here https://quizzesforyou.com/quiz/swiftbasicoperators

Ternary Conditional Operator(?:):

  • The ternary conditional operator is a special operator in programming languages like Swift, represented by the form: condition? true: false.

  • It provides a shorthand way to express if-else statements. The operator evaluates the “condition” and if it’s true, it returns “value 1”; otherwise, it returns “value 2”.

  • Example: In Swift, you can use the ternary operator to assign a value based on a condition. For instance:

let hasHeader \= true  
let rowHeight \= hasHeader ? 50 : 20  
// In this example, if hasHeader is true, rowHeight will be assigned 50,   
// otherwise it will be assigned 20.
Enter fullscreen mode Exit fullscreen mode

Nil-Coalescing Operator(??):

  • The nil-coalescing operator, represented as a ?? b, provides a convenient way to unwrap optional values or provide a default value if the optional is nil.

  • It’s used to streamline code when working with optional values and avoids verbose if-let or guard-let statements.

  • Example: In Swift, you can use the nil-coalescing operator to handle optional values and provide a fallback value. For instance:

let city: String? \= nil  
let nativeCity \= city?? "London"  
// nativeCity is equal to "London"
Enter fullscreen mode Exit fullscreen mode

Range Operators:

Closed Range Operator(…):

  • The closed range operator, represented as a…b, is used to define a range that includes all values from ‘a’ to ‘b’, including both endpoints.

  • It’s commonly used in loops and to represent a sequence of values.

  • Example: In Swift, you can use the closed range operator to iterate over a sequence of numbers or perform operations within a specific range. For instance:

for index in 1...5 {  
    print("\\(index) times 5 is \\(index \* 5)")  
}  
// This loop will print the multiplication table from 1 to 5.
Enter fullscreen mode Exit fullscreen mode

Half-Open Range Operator(..<):

  • The half-open range operator, represented as a..<b, defines a range that includes values from ‘a’ up to, but not including, ‘b’.

  • It’s useful when working with collections and sequences where you want to exclude the upper bound.

  • Example: In Swift, you can use the half-open range operator to iterate over a collection or perform operations up to a certain index. For instance:

let names \= \["Anna", "Alex", "Brian", "Jack"\]  
for i in 0..<names.count {  
    print("Person \\(i + 1) is called \\(names\[i\])")  
}  
// This loop will print each name in the names array with its corresponding index number.
Enter fullscreen mode Exit fullscreen mode

One-Sided Ranges:

  • One-sided ranges are used to represent ranges that continue as far as possible in one direction, either from the start or to the end.

  • They provide a concise way to work with partial ranges without specifying both endpoints.

for name in names\[2...\] {  
    print(name)  
}  
// This loop will print names starting from index 2 to the end of the names array.  

for name in names\[...2\] {  
    print(name)  
}  
// This loop will print names from the beginning of the names array up to index 2.
Enter fullscreen mode Exit fullscreen mode

Logical Operators:

Logical NOT Operator:

  • The logical NOT operator, represented as ! a, inverts the value of a Boolean expression.

  • It’s used to create a logical negation of a condition or Boolean value.

  • Example: In Swift, you can use the logical NOT operator to check if a condition is false or to invert a Boolean value. For instance:

let allowedEntry \= false  
if !allowedEntry {  
    print("ACCESS DENIED")  
}  
// This code will print "ACCESS DENIED" because the logical NOT operator inverts the value of allowedEntry, which is false.
Enter fullscreen mode Exit fullscreen mode

Logical AND Operator:

  • The logical AND operator, represented as a && b, returns true only if both ‘a’ and ‘b’ are true.

  • It’s commonly used to create compound conditions that require multiple expressions to be true.

  • Example: In Swift, you can use the logical AND operator to check if two conditions are both true. For instance:

let enteredDoorCode \= true  
let authorized \= false  
if enteredDoorCode && authorized {  
    print("Welcome!")  
} else {  
    print("ACCESS DENIED")  
}  
// This code will print "ACCESS DENIED" because authorized is false, even though enteredDoorCode is true.
Enter fullscreen mode Exit fullscreen mode

Logical OR Operator:

  • The logical OR operator, represented as a || b, returns true if either ‘a’ or ‘b’ (or both) are true.

  • It’s used when you want to check if at least one of the expressions is true.

  • Example: In Swift, you can use the logical OR operator to check if one of the conditions is true. For instance:

let hasDoorKey \= false  
let authorized\= true  
if hasDoorKey || authorized {  
    print("Welcome!")  
} else {  
    print("ACCESS DENIED")  
}  
// This code will print "Welcome!" because authorized is true, even though hasDoorKey is false.
Enter fullscreen mode Exit fullscreen mode

Checkout the interactive quiz of this story here https://quizzesforyou.com/quiz/swiftbasicoperators

Quizzes:

  1. What is the output of the following code snippet?
let x = true
let y = false
let z = x && y || x
print(z)
Enter fullscreen mode Exit fullscreen mode

a) true

b) false

Answer: A) true

The logical AND operator (&&) has higher precedence than the logical OR operator (||). So, the expression x && y is evaluated first, resulting in false. Then, the expression false || x is evaluated, resulting in true

2. What is the value of “finalColor” in the following code snippet?

let colorName: String? = blue
let defaultColor = red
let finalColor = colorName ?? defaultColor
Enter fullscreen mode Exit fullscreen mode

A) “blue”

B) “red”

C) nil

Answer: A) “blue”

Since colorName is not nil, the nil-coalescing operator (??) will unwrap the optional value and assign it to finalColor. Therefore, the value of finalColor will be “blue”.

3. What is the value of rowHeight in the following code snippet?

let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
Enter fullscreen mode Exit fullscreen mode

A) 60

B) 70

C) 90

Answer: C) 90

The ternary conditional operator (hasHeader ? 50 : 20) is used to determine the value to be added to contentHeight based on the value of hasHeader. Since hasHeader is true, the value of rowHeight will be contentHeight + 50, which results in 90.

4. What is the output of the following code snippet in Swift?

let range = …5
print(range.contains(4))
print(range.contains(7))
Enter fullscreen mode Exit fullscreen mode

A) true, false

B) false, true

C) true, true

Answer: A) true, false

The range …5 represents a range from negative infinity to 5, inclusive. The contains method is used to check if a given value is contained within the range. Therefore, range.contains(4) will return true, while range.contains(7) will return false.

5. What is the output of the following code snippet in Swift?

let names = \[Anna, Alex, Brian, Jack\]
let count = names.count
for i in 2..<count {
    print(names\[i\])
}
Enter fullscreen mode Exit fullscreen mode

A) Brian, Jack

B) Alex, Brian, Jack

C) Index out of range

Answer: A) Brian, Jack

The half-open range operator (2..<count) is used to iterate over the indices of the names array. The loop prints each element of the array based on the index.

6. What is the output of the following code?

let range = ..<5
print(range.contains(5))
Enter fullscreen mode Exit fullscreen mode

a) true

b) false

c) Compilation error

Answer: b) false

In this code, the half-open range operator (..<) is used to create a range that includes all values less than 5. The contains(_:) method is then used to check if the range contains the value 5. Since the range is half-open and doesn’t include the upper bound, the output is false.

7. What is the output of the following code?

let names = \[Alice, Bob, Charlie, David, Eve\]
let selectedNames = names\[13\]
print(selectedNames.count)
Enter fullscreen mode Exit fullscreen mode

a) 2

b) 3

c) 4

Answer: b) 3 the closed range operator (…) is used to create a range from index 1 to index 3. The range selects the elements at indexes 1, 2, and 3 from the names array, which are “Bob”, “Charlie”, and “David”.


Visit https://quizzesforyou.com for more such quizzes

References: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/basicoperators

Top comments (0)