Bird
Raised Fist0
iOS Swiftmobile~20 mins

Collections (Array, Dictionary, Set) in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Collections Demo
This screen shows examples of three common collections in Swift: an Array, a Dictionary, and a Set. It displays their contents in separate sections so you can see how each collection works.
Target UI
-------------------------
| Collections Demo       |
|-----------------------|
| Array:                |
| - Apple               |
| - Banana              |
| - Cherry              |
|-----------------------|
| Dictionary:           |
| - A: Apple            |
| - B: Banana           |
| - C: Cherry           |
|-----------------------|
| Set:                  |
| - Apple               |
| - Banana              |
| - Cherry              |
-------------------------
Display an Array of strings labeled 'Array' with three fruit names.
Display a Dictionary with single-letter keys and fruit names as values labeled 'Dictionary'.
Display a Set of strings labeled 'Set' with the same fruit names.
Use SwiftUI VStack and Text views to layout the content clearly.
Each collection section should have a title and list its items below.
Starter Code
iOS Swift
import SwiftUI

struct CollectionsDemoView: View {
    // TODO: Define the collections here

    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            // TODO: Add UI for Array

            // TODO: Add UI for Dictionary

            // TODO: Add UI for Set
        }
        .padding()
        .navigationTitle("Collections Demo")
    }
}

struct CollectionsDemoView_Previews: PreviewProvider {
    static var previews: some View {
        CollectionsDemoView()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
iOS Swift
import SwiftUI

struct CollectionsDemoView: View {
    let fruitsArray = ["Apple", "Banana", "Cherry"]
    let fruitsDictionary = ["A": "Apple", "B": "Banana", "C": "Cherry"]
    let fruitsSet: Set<String> = ["Apple", "Banana", "Cherry"]

    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            VStack(alignment: .leading, spacing: 5) {
                Text("Array:")
                    .font(.headline)
                ForEach(fruitsArray, id: \.self) { fruit in
                    Text("- \(fruit)")
                }
            }

            VStack(alignment: .leading, spacing: 5) {
                Text("Dictionary:")
                    .font(.headline)
                ForEach(fruitsDictionary.sorted(by: { $0.key < $1.key }), id: \.key) { key, value in
                    Text("- \(key): \(value)")
                }
            }

            VStack(alignment: .leading, spacing: 5) {
                Text("Set:")
                    .font(.headline)
                ForEach(Array(fruitsSet).sorted(), id: \.self) { fruit in
                    Text("- \(fruit)")
                }
            }
        }
        .padding()
        .navigationTitle("Collections Demo")
    }
}

struct CollectionsDemoView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            CollectionsDemoView()
        }
    }
}

We defined three collections: an Array, a Dictionary, and a Set, each holding fruit names. The Array keeps order, so we list its items directly. The Dictionary is sorted by keys to show items in order. The Set is unordered, so we convert it to an Array and sort it before displaying. Each collection is shown in its own VStack with a bold title and a list of items below. This layout helps beginners see how these collections store and present data differently.

Final Result
Completed Screen
-------------------------
| Collections Demo       |
|-----------------------|
| Array:                |
| - Apple               |
| - Banana              |
| - Cherry              |
|-----------------------|
| Dictionary:           |
| - A: Apple            |
| - B: Banana           |
| - C: Cherry           |
|-----------------------|
| Set:                  |
| - Apple               |
| - Banana              |
| - Cherry              |
-------------------------
The screen shows three sections labeled Array, Dictionary, and Set.
Each section lists the fruit names as text lines.
No interactive elements; this screen is for display only.
Stretch Goal
Add a button that shuffles the Array and updates the displayed order when tapped.
💡 Hint
Use @State to hold the array and call shuffle() inside the button's action closure.

Practice

(1/5)
1. Which Swift collection type keeps the order of items and allows duplicates?
easy
A. Array
B. Dictionary
C. Set
D. Tuple

Solution

  1. Step 1: Understand collection types

    Arrays keep the order of elements and allow duplicates, dictionaries store key-value pairs, and sets store unique unordered items.
  2. Step 2: Match collection behavior

    Since the question asks for ordered and duplicate-allowed collection, Array fits this description.
  3. Final Answer:

    Array -> Option A
  4. Quick Check:

    Ordered + duplicates = Array [OK]
Hint: Remember: Arrays keep order and duplicates [OK]
Common Mistakes:
  • Confusing sets with arrays because both store multiple items
  • Thinking dictionaries keep order like arrays
  • Assuming tuples are collections like arrays
2. Which of the following is the correct way to declare an empty dictionary in Swift?
easy
A. var dict = Set<String>()
B. var dict = [Int]()
C. var dict = [String: Int]()
D. var dict = Array<Int>()

Solution

  1. Step 1: Identify dictionary syntax

    In Swift, dictionaries are declared with key and value types inside square brackets separated by a colon, e.g., [KeyType: ValueType]().
  2. Step 2: Check options

    var dict = [String: Int]() uses [String: Int]() which is correct for an empty dictionary with String keys and Int values. Others are array or set declarations.
  3. Final Answer:

    var dict = [String: Int]() -> Option C
  4. Quick Check:

    Dictionary syntax = [Key: Value]() [OK]
Hint: Dictionaries use [Key: Value]() syntax [OK]
Common Mistakes:
  • Using [Int]() which is an array, not dictionary
  • Confusing sets with dictionaries
  • Missing colon between key and value types
3. What will be the output of this Swift code?
let fruits: Set<String> = ["apple", "banana", "apple", "orange"]
print(fruits.count)
medium
A. 4
B. Error
C. 2
D. 3

Solution

  1. Step 1: Understand Set behavior

    Sets store unique elements only, so duplicates are removed automatically.
  2. Step 2: Count unique fruits

    The array has "apple" twice, so unique items are "apple", "banana", "orange" which is 3.
  3. Final Answer:

    3 -> Option D
  4. Quick Check:

    Set removes duplicates, count = 3 [OK]
Hint: Sets remove duplicates, count unique items only [OK]
Common Mistakes:
  • Counting duplicates as separate items
  • Thinking sets keep order and duplicates
  • Expecting a runtime error for duplicates
4. Identify the error in this Swift dictionary code:
var capitals = ["France": "Paris", "Japan": "Tokyo"]
capitals["France"] = "Lyon"
capitals["Germany"] = "Berlin"
print(capitals["Germany"])
medium
A. Adding new key-value pair is not allowed
B. No error, code runs and prints Optional("Berlin")
C. Cannot assign new value to existing key
D. Dictionary keys must be Int, not String

Solution

  1. Step 1: Check dictionary mutation rules

    Dictionaries in Swift are mutable if declared with var, so you can update existing keys and add new ones.
  2. Step 2: Analyze code behavior

    Updating "France" to "Lyon" and adding "Germany" with "Berlin" is valid. Printing capitals["Germany"] returns Optional("Berlin") because dictionary lookup returns an optional.
  3. Final Answer:

    No error, code runs and prints Optional("Berlin") -> Option B
  4. Quick Check:

    Mutable dictionary updates and adds keys [OK]
Hint: Mutable dictionaries allow adding and updating keys [OK]
Common Mistakes:
  • Thinking dictionaries are immutable by default
  • Expecting print to show value without Optional
  • Believing keys must be Int type
5. Given this code, what is the resulting dictionary?
let names = ["Anna", "Bob", "Anna", "Cara"]
var counts = [String: Int]()
for name in names {
  counts[name, default: 0] += 1
}
print(counts)
hard
A. ["Anna": 2, "Bob": 1, "Cara": 1]
B. ["Anna": 1, "Bob": 1, "Cara": 1]
C. ["Anna": 3, "Bob": 1, "Cara": 1]
D. Syntax error due to default value

Solution

  1. Step 1: Understand dictionary default value usage

    The syntax counts[name, default: 0] returns the current value for key or 0 if key is missing, allowing safe increment.
  2. Step 2: Count occurrences in array

    "Anna" appears twice, "Bob" and "Cara" once each, so counts dictionary will have Anna: 2, Bob: 1, Cara: 1.
  3. Final Answer:

    ["Anna": 2, "Bob": 1, "Cara": 1] -> Option A
  4. Quick Check:

    Counting duplicates with default 0 increments [OK]
Hint: Use dictionary[key, default: 0] += 1 to count items [OK]
Common Mistakes:
  • Expecting syntax error from default value usage
  • Counting duplicates as 1 only
  • Confusing dictionary keys and values
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard