Swift Quiz #05: Swift Arrays

quizzesforyouquizzesforyou
8 min read

Topic: Swift Arrays

Check out the interactive quiz https://quizzesforyou.com/quiz/swiftarrays

Checkout All Swift Quizzes

In Swift, an array is a collection type that allows you to store multiple values of the same type in an ordered list. Arrays are used to group related values together and access them using an index.

Key Concepts:

  1. Mutability: Swift arrays can be mutable or immutable depending on whether you declare them as variables (var) or constants (let). Immutable arrays cannot be modified once defined, while mutable arrays can have elements added, removed, or modified.

  2. Type Safety: Swift arrays are strongly typed, meaning they can only store values of the same type. Once you define the type of an array, you cannot store values of a different type in it.

  3. Dynamic Size: Swift arrays have a dynamic size, which means they can grow or shrink in length as needed. You can append elements to the end of an array using the append() method, insert elements at specific positions using the insert(_:at:) method, and remove elements using the remove(at:) method.

  4. Array Literal: Array can be initialized using an array literal, which is a shorthand way of defining an array. Array literals are created by enclosing a comma-separated list of values inside square brackets []

  5. Value Semantics: Arrays in Swift have value semantics. When you assign an array to a new variable or pass it as a parameter to a function, a new copy of the array is created. This ensures that modifications to one array do not affect other copies.

Quick Refresher:

1. Creating and Initializing Arrays in Swift:

  • Empty Arrays: To create an empty array, developers can utilize the initializer syntax or the array literal

  • Initializing with Default Values: Arrays can be initialized with a specific size and default values using the Array(repeating:count:) initializer

  • Initializing with Values: Values can be directly assigned to an array using an array literal

//Empty Arrays:  

var someInts: \[Int\] \= \[\]  
var anotherInts \= \[Int\]()  

//Initializing with Default Values:  

var threeDoubles \= Array(repeating: 0.0, count: 3)  

// Initializing with Values  
var shoppingList: \[String\] \= \["Eggs", "Milk", "Flour"\]

2. Accessing and Modifying Arrays

  • Count and Empty Check: number of items in an array can be determined using the count property

  • To check if an array is empty, use the isEmpty property

// count  
print("The shopping list contains \\(shoppingList.count) items.")  

// Empty check   

if shoppingList.isEmpty {  
    print("The shopping list is empty.")  
} else {  
    print("The shopping list isn't empty.")  
}
  • Appending and Modifying: Elements can be added to an array using the append(_:) method or the += operator. To modify an existing element, subscript syntax can be used.
// Appending  

shoppingList.append("Bread")  
shoppingList += \["Butter", "Sugar"\]  

//Subscript  

shoppingList\[0\] \= "Bananas"
  • Inserting and Removing Elements: Items can be inserted at a specific index using the insert(_:at:) method:

  • To remove an element at a given index, use the remove(at:) method

// Insert  
shoppingList.insert("Apples", at: 1)  

//Remove   
let removedItem \= shoppingList.remove(at: 2)

3. Combining and Transforming Arrays

  • Combining Arrays: Two arrays with compatible types can be combined using the + operator:

  • Transforming Arrays: Swift provides powerful higher-order functions to transform arrays. For example, the map(_:), filter, reduce, flatmap functions can be used to apply a transformation to each element:


// combining Arrays  

var fruits \= \["Bananas", "Apples"\]  
var vegetables \= \["Carrots", "Broccoli"\]  
var groceries \= fruits + vegetables  

// Transforming  

let numbers \= \[1, 2, 3, 4, 5\]  
let squaredNumbers \= numbers.map { $0 \* $0 }  

// Sorting an array  
let sortedNumbers \= numbers.sorted()  

// Filtering an array  
let evenNumbers \= numbers.filter { $0 % 2 \== 0 }

4. Iterating over Arrays

  • For-In Loop: Arrays can be iterated using a for-in loop

  • Enumerating Arrays To access both the index and value of each item in an array, utilize the enumerated() method


for (index, item) in shoppingList.enumerated() {  
    print("Item \\(index + 1): \\(item)")  
}  

// Enumerating  
for (index, item) in shoppingList.enumerated() {  
    print("Item \\(index + 1): \\(item)")  
}

5. Common Array Operations:

  • Swift arrays provide several useful operations, such as sorting, filtering, and searching.

6. Storing Callbacks in Arrays:

Arrays in Swift can store values of any type, including functions or closures. This feature enables the storage of callbacks or event handlers in an array, facilitating dynamic behavior in code.

typealias Callback \= () -> Void  

var callbacks: \[Callback\] \= \[\]  

func performTask(withCallback callback: @escaping Callback) {  
    callbacks.append(callback)  
}  

func executeCallbacks() {  
    for callback in callbacks {  
        callback()  
    }  
}

Check out the interactive quiz https://quizzesforyou.com/quiz/swiftarrays

  1. What is the output?
var numbers \= \[1, 2, 3, 4, 5\]  
let transformedNumbers \= numbers.map { $0 \* 2 }  
print(transformedNumbers)

A) [2, 4, 6, 8, 10]

B) [1, 2, 3, 4, 5]

C) [1, 4, 9, 16, 25]

Answer: A

The map(_:) function transforms each element in the numbers array by multiplying it by 2, resulting in the array [2, 4, 6, 8, 10].

2. Which method is used to find the first index of a specific element in an array?

A) index(of:)

B) findIndex(of:)

C) firstIndex(of:)

Answer: C

The firstIndex(of:) method is used to find the first index of a specific element in an array.

3. What is the output?

let names = \["Alice", "Bob", "Charlie"\]  
let result = names.allSatisfy { $0.count >= 3 }  
print(result)

a) true

b) [“Alice”, “Charlie”]

c) [true, true, true]

Answer: a) true

The allSatisfy function is used to check if all elements in the array satisfy a given condition. In this case, the closure { $0.count >= 3 } checks if the length of each name in the names array is greater than or equal to 3. Since all the names in the array ("Alice", "Bob", "Charlie") have lengths of 3 or more characters, the condition is satisfied for all elements, and the output will be true.

4. What is the output?

let numbers \= \[1, 2, 3, 4, 5\]  
let result \= numbers.reduce(3) { $0 + $1 }  
print(result)

a) 15

b) 18

c) 5

Answer: b) 18

The reduce function is used to combine all elements of the numbers array into a single value (result). The initial value is set to 3 (reduce(3)), and the closure $0 + $1 is used to add each element of the array to the accumulated value. So, the output will be the sum of all numbers in the array, which is 18.

5. Which method can be used to check if an array contains a specific element?

A) contains(_:)

B) includes(_:)

C) has(_:)

Answer: A

The contains(_:) method is used to check if an array contains a specific element.

6. What is the output?

let numbers \= \[1, 2, 3, 4, 5\]  
let result \= numbers.filter { $0 % 2 \== 0 }  
              .flatMap { Array(repeating: $0, count: $0) }  
print(result)

a) [2, 2, 4, 4, 4, 4]

b) [0, 0, 0, 0, 0, 0]

c) [[0,0],[0,0,0,0]]

Answer: a) [2, 2, 4, 4, 4, 4]

the filter function is first used to create a new array that contains only the even numbers from the numbers array. Then, the flatMap function is applied to transform each even number into an array of repeating numbers. The resulting array is flattened, resulting in [2, 2, 4, 4, 4], which contains the repeating numbers for each even number in the original array.

7. What is the output?

let names = \["Alice", "Bob", "Charlie"\]  
let result = names.allSatisfy { $0.count >= 3 }  
print(result)

a) true

b) [“Alice”, “Charlie”]

c) [true, true, true]

Answer: a) true

The allSatisfy function is used to check if all elements in the array satisfy a given condition. In this case, the closure { $0.count >= 3 } checks if the length of each name in the names array is greater than or equal to 3. Since all the names in the array ("Alice", "Bob", "Charlie") have lengths of 3 or more characters, the condition is satisfied for all elements, and the output will be true.

8. What is the output?

let names \= \["Alice", "Bob", "Charlie", "David"\]  
let result \= names.compactMap { $0.count \> 4 ? $0 : nil }  
print(result)

a) [“Alice”, “Bob”, “Charlie”, “David”]

b) [“Alice”, “Charlie”, “David”]

c) [“Bob”, “David”]

Answer: b) [“Alice”, “Charlie”, “David”]

The compactMap function is used to transform each element in the array and remove any resulting nil values. In this case, the closure { $0.count > 4 ? $0 : nil } checks if the length of each name is greater than 4. If it is, the name is returned; otherwise, nil is returned and filtered out. So, the output will be an array containing only the names with lengths greater than 4: [“Alice”, “Charlie”, “David”].

9. What is the difference between map and flatMap when dealing with optionals?

A) map unwraps optionals, while flatMap keeps the optionals intact.

B) map transforms optionals, while flatMap unwraps optionals.

C) There is no difference between map and flatMap when dealing with optionals.

Answer: B

When applied to optionals, map transforms the underlying value if it exists, while flatMap unwraps the optional and applies a transformation that may also return an optional value.

10. What is the output?

let words = \["Hello", "World", "Swift"\]  
let result = words.joined(separator: " ")  
print(result)

a) “HelloWorldSwift”

b) “Hello World Swift”

c) “Hello, World, Swift”

Answer: b) “Hello World Swift”

The joined(separator:) function is used to concatenate the elements of an array into a single string, separated by a specified separator. In this case, the elements of the words array are joined into a single string with a space separator. So, the output will be "Hello World Swift" with spaces between the words.


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

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

0
Subscribe to my newsletter

Read articles from quizzesforyou directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

quizzesforyou
quizzesforyou