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

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

解决方法

当然可以.

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

Files and Initialization开始,Apple 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上,@ UapppplicationMain是应用程序入口点.它会自动为您完成整个启动工作.但是在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

UIApplicationMain initializationMatt Neuburg提供.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...