Xcode 中的单个 .swift 文件是否可以包含 iOS 应用程序的完整源代码?

Can a single .swift file in Xcode contain entire source code of an iOS app?

换句话说,Swift Xcode 中的代码可以像在 Playground 文件中那样运行吗?

是的,但 AppDelegate 除外。不建议这样做,但在一个文件中可以有多个 类.

是的,如果您真的想用分号结束您的行,您可以这样做,就像您可以在一行代码中编写所有代码一样。虽然,这绝对不推荐,因为它会导致很多混乱,而且您不得不费心去弄乱原始的组织文件。

当然可以。

这个特殊文件叫做 main.swift,它的行为就像一个 Playground 文件。

来自 Files and Initialization,Apple post 上的一个 Swift 博客:

… 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”.

但是,在 iOS 上,@UIApplicationMain 是应用程序入口点。它会自动为您完成整个启动工作。但是在 iOS 应用程序的 main.swift 中,您必须手动初始化它。

在 Swift 3.1 中,您的 main.swift 文件应该这样开始:

// 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

provided by Matt Neuburg.

是的,因为所有文件都可以在另一个文件上看到顶级代码。但出于同样的原因,让您的工作空间变得混乱毫无意义。