0
0
Swiftprogramming~20 mins

Main entry point and @main attribute in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Main Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a Swift program with @main attribute
What is the output of this Swift program using the @main attribute?
Swift
import Foundation

@main
struct HelloWorld {
    static func main() {
        print("Hello, Swift!")
    }
}
ANo output
BCompilation error: Missing main.swift file
CRuntime error: main function not found
DHello, Swift!
Attempts:
2 left
💡 Hint
The @main attribute marks the program's entry point.
Predict Output
intermediate
2:00remaining
Output when multiple @main structs exist
What happens if you compile this Swift code with two structs marked @main?
Swift
import Foundation

@main
struct FirstApp {
    static func main() {
        print("First")
    }
}

@main
struct SecondApp {
    static func main() {
        print("Second")
    }
}
ACompilation error: Multiple @main types found
BPrints "First" then "Second"
CPrints "Second" only
DRuntime error: ambiguous entry point
Attempts:
2 left
💡 Hint
Swift requires exactly one @main entry point.
🔧 Debug
advanced
2:00remaining
Why does this @main struct fail to compile?
This Swift program uses @main but fails to compile. Why? import Foundation @main struct App { func main() { print("Hello") } }
Swift
import Foundation

@main
struct App {
    func main() {
        print("Hello")
    }
}
AMissing import of SwiftUI
BThe struct must be a class to use @main
Cmain() must be static, but it is an instance method
Dmain() must return an Int
Attempts:
2 left
💡 Hint
The entry point method must be static.
🧠 Conceptual
advanced
1:30remaining
Purpose of the @main attribute in Swift
What is the main purpose of the @main attribute in a Swift program?
ATo enable multithreading in the program
BTo mark the program's entry point where execution starts
CTo import the main module automatically
DTo define the main user interface layout
Attempts:
2 left
💡 Hint
Think about where the program begins running.
Predict Output
expert
2:30remaining
Output of a Swift program using @main with async main
What is the output of this Swift program using an async main method with @main?
Swift
import Foundation

@main
struct AsyncApp {
    static func main() async {
        try? await Task.sleep(nanoseconds: 1_000_000_000) // 1 second
        print("Async Hello")
    }
}
AAsync Hello
BCompilation error: async main not supported
CRuntime error: Task.sleep not allowed in main
DNo output, program exits immediately
Attempts:
2 left
💡 Hint
Swift 5.5+ supports async main methods with @main.