In other words, can Swift code in Xcode behave like it does in a Playground file?
-
3This was asked a few days ago but I can't find it now. Did you try it? Why do want to do this? What is your question/issue? – rmaddy Apr 11 '17 at 17:50
4 Answers
It certainly can.
This special file is called main.swift
and it behaves just like a Playground file.
From Files and Initialization, a post on Apple Swift Blog:
… The “main.swift” file can contain top-level code, and the order-dependent rules apply as well. In effect, the first line of code to run in “main.swift” is implicitly defined as the main entrypoint for the program. This allows the minimal Swift program to be a single line — as long as that line is in “main.swift”.
However, on iOS, @UIApplicationMain
is the application entry point. It does the whole startup work for you automatically. But in main.swift
of an iOS app, you have to initialize it manually.
In Swift 3.1, your main.swift
file should begin like this:
// main.swift
import Foundation
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
UIApplicationMain(
CommandLine.argc,
UnsafeMutableRawPointer(CommandLine.unsafeArgv)
.bindMemory(
to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)),
nil,
NSStringFromClass(AppDelegate.self)
)
// Your code begins here
UIApplicationMain initialization provided by Matt Neuburg.
Yes it does, except the AppDelegate though. It is not recommended to do that, but in one file you can have multiple classes.

- 140
- 10
Yes, you could do this just as you could write all your code on one line of code if you really wanted to with semicolons to end your lines. Although, this is definitely not recommended as it can cause lots of confusion and you have to bother messing with the original organized files.

- 72
- 5
yes, because all files can see on another as top level code. but for the same reason its pointless to clutter your workspace.

- 29
- 6