The @main attribute marks MyApp as the entry point, so main() runs first.
Step 2: Trace the function calls
main() prints "Start" then calls run(), which prints "Running".
Final Answer:
Start
Running -> Option D
Quick Check:
main() prints Start then run() prints Running [OK]
Hint: Follow the call order inside static main() [OK]
Common Mistakes:
Assuming run() runs before main()
Forgetting to call run() inside main()
Thinking @main runs run() automatically
4. Identify the error in this Swift program using @main:
@main class App {
func main() {
print("Hello")
}
}
medium
A. The @main attribute cannot be used on a class.
B. The main() method must be static.
C. The print statement is invalid inside main().
D. The class must be a struct instead.
Solution
Step 1: Check the main() method signature
The @main type must have a staticmain() method to serve as the entry point.
Step 2: Identify the missing static keyword
Here, main() is an instance method, missing static, causing a compile error.
Final Answer:
The main() method must be static. -> Option B
Quick Check:
main() must be static in @main type [OK]
Hint: Static main() is required inside @main type [OK]
Common Mistakes:
Omitting static keyword on main()
Thinking @main can't be on classes
Confusing instance and static methods
5. You want to create a Swift program that prints "Welcome!" only if a condition is true at startup. Using @main, which is the best way to implement this?
hard
A. struct App {
static func main() {
if true {
print("Welcome!")
}
}
}
B. @main struct App {
func main() {
if true {
print("Welcome!")
}
}
}
C. @main struct App {
static func main() {
if true {
print("Welcome!")
}
}
}
D. @main func main() {
if true {
print("Welcome!")
}
}
Solution
Step 1: Use @main on a type with static main()
The program must have a type marked with @main and a static main() method to run at startup.