Bird
Raised Fist0
Swiftprogramming~20 mins

Limitations and best practices in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Limitations and Best Practices Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Understanding value type limitations in Swift structs

What is the output of this Swift code snippet?

Swift
struct Counter {
    var count = 0
    mutating func increment() {
        count += 1
    }
}

var c1 = Counter()
let c2 = c1
c1.increment()
print(c1.count, c2.count)
A1 0
B1 1
C0 0
D0 1
Attempts:
2 left
💡 Hint

Remember that structs are value types and copying creates independent instances.

❓ Predict Output
intermediate
2:00remaining
Best practice for optional unwrapping

What will be printed by this Swift code?

Swift
var name: String? = "Alice"
if let unwrappedName = name {
    print("Hello, \(unwrappedName)!")
} else {
    print("No name provided.")
}
Anil
BNo name provided.
COptional("Alice")
DHello, Alice!
Attempts:
2 left
💡 Hint

Check how optional binding works with if let.

🔧 Debug
advanced
3:00remaining
Identify the cause of a retain cycle

Which line in the following Swift code causes a retain cycle leading to a memory leak?

Swift
class Person {
    var name: String
    var apartment: Apartment?
    init(name: String) { self.name = name }
    deinit { print("Person \(name) is being deinitialized") }
}

class Apartment {
    var unit: String
    var tenant: Person?
    init(unit: String) { self.unit = unit }
    deinit { print("Apartment \(unit) is being deinitialized") }
}

var john: Person? = Person(name: "John")
var unit4A: Apartment? = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john
Ajohn!.apartment = unit4A
Bunit4A!.tenant = john
Cvar tenant: Person? in Apartment class
Dvar apartment: Apartment? in Person class
Attempts:
2 left
💡 Hint

Think about strong references between classes causing retain cycles.

📝 Syntax
advanced
2:00remaining
Which option correctly declares a protocol with an associated type?

Choose the correct Swift syntax for declaring a protocol with an associated type named Item.

A
protocol Container {
    associatedtype Item
    func append(_ item: Item)
}
B
protocol Container {
    typealias Item
    func append(_ item: Item)
}
C
protocol Container {
    var Item: Type
    func append(_ item: Item)
}
D
protocol Container {
    associatedtype Item = Any
    func append(_ item: Item)
}
Attempts:
2 left
💡 Hint

Recall the keyword for declaring associated types in protocols.

🧠 Conceptual
expert
2:30remaining
Best practice to avoid force unwrapping optionals

Which approach is considered the best practice to safely handle optionals in Swift and avoid runtime crashes?

AUse <code>as!</code> to cast optionals to non-optionals directly.
BUse force unwrapping <code>!</code> whenever you are sure the optional contains a value.
CUse optional binding with <code>if let</code> or <code>guard let</code> to unwrap optionals safely.
DConvert optionals to implicitly unwrapped optionals to avoid unwrapping syntax.
Attempts:
2 left
💡 Hint

Think about safety and avoiding crashes.

Practice

(1/5)
1. Which of the following is a known limitation of Swift as a programming language?
easy
A. Swift does not support multiple inheritance for classes.
B. Swift cannot use functions.
C. Swift does not allow variables.
D. Swift cannot perform arithmetic operations.

Solution

  1. Step 1: Understand Swift class inheritance

    Swift allows classes to inherit from only one superclass, so multiple inheritance is not supported.
  2. Step 2: Evaluate other options

    Swift supports functions, variables, and arithmetic operations fully, so options B, C, and D are incorrect.
  3. Final Answer:

    Swift does not support multiple inheritance for classes. -> Option A
  4. Quick Check:

    Multiple inheritance = Not supported [OK]
Hint: Remember: Swift classes have single inheritance only [OK]
Common Mistakes:
  • Thinking Swift supports multiple inheritance like some other languages
  • Confusing protocol inheritance with class inheritance
  • Assuming Swift lacks basic features like functions or variables
2. Which of the following is the correct way to safely unwrap an optional in Swift?
easy
A. optionalValue = value
B. print(optionalValue!)
C. optionalValue = nil
D. if let value = optionalValue { print(value) }

Solution

  1. Step 1: Identify safe optional unwrapping

    Using 'if let' safely unwraps an optional only if it contains a value.
  2. Step 2: Check other options

    print(optionalValue!) force unwraps and can crash if nil; C and D are assignments, not unwrapping.
  3. Final Answer:

    if let value = optionalValue { print(value) } -> Option D
  4. Quick Check:

    Safe unwrapping = if let [OK]
Hint: Use 'if let' to unwrap optionals safely [OK]
Common Mistakes:
  • Using force unwrap (!) without checking for nil
  • Confusing assignment with unwrapping
  • Ignoring optional safety and risking runtime crashes
3. What will be the output of the following Swift code?
let numbers = [1, 2, 3, 4]
let doubled = numbers.map { $0 * 2 }
print(doubled)
medium
A. Error: map is not a function
B. [1, 2, 3, 4]
C. [2, 4, 6, 8]
D. [4, 8, 12, 16]

Solution

  1. Step 1: Understand the map function

    The map function applies the closure to each element, multiplying each by 2.
  2. Step 2: Calculate the result

    Each number doubles: 1*2=2, 2*2=4, 3*2=6, 4*2=8, so the array is [2, 4, 6, 8].
  3. Final Answer:

    [2, 4, 6, 8] -> Option C
  4. Quick Check:

    map doubles each element = [2, 4, 6, 8] [OK]
Hint: Remember map transforms each element in the array [OK]
Common Mistakes:
  • Thinking map modifies the original array
  • Confusing map with filter or reduce
  • Expecting an error due to misunderstanding map
4. Identify the error in the following Swift code snippet:
var name: String?
print(name.count)
medium
A. The 'count' property does not exist for String.
B. Optional value 'name' must be unwrapped before accessing 'count'.
C. Variable 'name' cannot be declared as optional.
D. print statement syntax is incorrect.

Solution

  1. Step 1: Analyze optional usage

    'name' is an optional String, so accessing 'count' directly is unsafe and causes an error.
  2. Step 2: Understand Swift optional rules

    You must unwrap 'name' safely before accessing its properties to avoid runtime errors.
  3. Final Answer:

    Optional value 'name' must be unwrapped before accessing 'count'. -> Option B
  4. Quick Check:

    Access optional property = unwrap first [OK]
Hint: Always unwrap optionals before accessing their properties [OK]
Common Mistakes:
  • Trying to access properties on optionals directly
  • Ignoring the need for safe unwrapping
  • Assuming optional variables behave like normal variables
5. You want to create a dictionary from an array of names where keys are names and values are the length of each name, but only include names longer than 3 characters. Which Swift code snippet follows best practices and limitations correctly?
hard
A. let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.filter { $0.count > 3 }.map { ($0, $0.count) })
B. let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.map { ($0, $0.count) })
C. let names = ["Amy", "John", "Kate"] var dict = [String: Int]() for name in names { dict[name] = name.count }
D. let names = ["Amy", "John", "Kate"] let dict = names.reduce(into: [:]) { $0[$1] = $1.count }

Solution

  1. Step 1: Understand the requirement

    We need a dictionary with names longer than 3 characters as keys and their lengths as values.
  2. Step 2: Analyze each option

    let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.map { ($0, $0.count) }) includes all names, ignoring length filter. let names = ["Amy", "John", "Kate"] var dict = [String: Int]() for name in names { dict[name] = name.count } declares dict as var (mutable), but does not filter names. let names = ["Amy", "John", "Kate"] let dict = names.reduce(into: [:]) { $0[$1] = $1.count } includes all names without filtering. let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.filter { $0.count > 3 }.map { ($0, $0.count) }) filters names with count > 3 before mapping to dictionary, following best practice and limitation.
  3. Final Answer:

    let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.filter { $0.count > 3 }.map { ($0, $0.count) }) -> Option A
  4. Quick Check:

    Filter then map to dictionary = let names = ["Amy", "John", "Kate"] let dict = Dictionary(uniqueKeysWithValues: names.filter { $0.count > 3 }.map { ($0, $0.count) }) [OK]
Hint: Filter first, then map to dictionary for clean code [OK]
Common Mistakes:
  • Not filtering names before creating dictionary
  • Using mutable dictionary without filtering
  • Ignoring best practice of chaining filter and map
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