Understanding Limitations and Best Practices in Swift
📖 Scenario: You are building a simple Swift program to manage a list of tasks. You will learn about some common limitations in Swift programming and best practices to write clean, safe, and efficient code.
🎯 Goal: Create a Swift program that stores tasks, limits the number of tasks, and prints them following best practices.
📋 What You'll Learn
Create an array to hold task names
Set a maximum number of tasks allowed
Add tasks only if the limit is not exceeded
Print all tasks clearly
💡 Why This Matters
🌍 Real World
Managing tasks is a common need in apps like to-do lists, reminders, and project planners. Limiting tasks helps keep the app organized and prevents overload.
💼 Career
Understanding how to manage collections, use constants, write functions, and apply conditions are fundamental skills for any Swift developer working on real-world applications.
Progress0 / 4 steps
1
Create the initial task list
Create an empty array called tasks of type String to hold task names.
Swift
Hint
Use var to create a variable array of strings.
2
Set a maximum task limit
Create a constant called maxTasks and set it to 5 to limit the number of tasks.
Swift
Hint
Use let to create a constant for the maximum number of tasks.
3
Add tasks with limit check
Write a function called addTask that takes a String parameter task. Inside the function, add the task to tasks only if the number of tasks is less than maxTasks. Otherwise, print "Task limit reached".
Swift
Hint
Use if to check the count of tasks before adding.
4
Print all tasks
Use a for loop with variable task to iterate over tasks and print each task.
Swift
Hint
Use print(task) inside the loop to show each task.
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
Step 1: Understand Swift class inheritance
Swift allows classes to inherit from only one superclass, so multiple inheritance is not supported.
Step 2: Evaluate other options
Swift supports functions, variables, and arithmetic operations fully, so options B, C, and D are incorrect.
Final Answer:
Swift does not support multiple inheritance for classes. -> Option A
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
Step 1: Identify safe optional unwrapping
Using 'if let' safely unwraps an optional only if it contains a value.
Step 2: Check other options
print(optionalValue!) force unwraps and can crash if nil; C and D are assignments, not unwrapping.
Final Answer:
if let value = optionalValue { print(value) } -> Option D
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
Step 1: Understand the map function
The map function applies the closure to each element, multiplying each by 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].
Final Answer:
[2, 4, 6, 8] -> Option C
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
Step 1: Analyze optional usage
'name' is an optional String, so accessing 'count' directly is unsafe and causes an error.
Step 2: Understand Swift optional rules
You must unwrap 'name' safely before accessing its properties to avoid runtime errors.
Final Answer:
Optional value 'name' must be unwrapped before accessing 'count'. -> Option B
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
Step 1: Understand the requirement
We need a dictionary with names longer than 3 characters as keys and their lengths as values.
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.
Final Answer:
let names = ["Amy", "John", "Kate"]
let dict = Dictionary(uniqueKeysWithValues: names.filter { $0.count > 3 }.map { ($0, $0.count) }) -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.