
关键字
| #file | 获取所在的文件 |
|---|---|
| #function | 获取所在的方法 |
| #line | 获取所在的行号 |
| #column | 获取所在的列数 |
行控制语句
sourceLocation(file: String, line: Int) 会改变该语句之后的 #file 和 #line 值,line 必须大于 1
#sourceLocation() 重置恢复默认的 #file 和 #line 值
#sourceLocation(file: "hj.swift", line: 1)print(#file, #line) // hj.swift 1#sourceLocation()print(#file, #line) // ...xx.swift 66
编译控制语句
使用 #if - #elseif - #else - #endif 可以根据条件控制是否进行代码编译
#if CompileCondition1// ...#elseif CompileCondition2// ...#else// ...#endif
编译条件 CompileCondition 可以是 true 和 false 的字面量,也可以是使用 -D 命令行标志的标识符,或者是下列表格中的任意一个平台检测函数。
| 函数 | 可选参数值 | 说明 |
|---|---|---|
| os() | OSX, iOS, watchOS, tvOS, Linux | 运行系统 |
| arch() | i386, x86_64, arm, arm64 | 处理器架构 |
| swift() | >= 后跟版本号 | Swift 语言版本 |
举例:
#if os(iOS) || os(macOS)// ...#endif#if arch(arm) || arch(arm64)// ...#endif#if swift(<5) && swift(>=3)// ...#endif#if DEBUG// ...#endif#if canImport(Foundation)// ...#endif#if targetEnvironment(simulator)// ...#endif
如果宏 DEBUG 无效,可以在 TARGETS / Build Settings / Swift Complier - Custom Flags / Other Swift Flags / DEBUG 添加 -D DEBUG
API 可用性检查
Swift 拥有内置的对 API 可用性的检查功能。编译器在 SDK 中使用可用性信息来确保在你项目中明确的 API 都是可用的。如果你尝试使用一个不可用的 API 的话,Swift 会在编译时报告一个错误。
if #available(platform name version, ..., *) {// statements to execute if the APIs are available} else {// fallback statements to execute if the APIs are unavailable}
在这个通用的格式中,可用性条件接收平台的名称和版本列表。你可以使用 iOS,macOS 和 watchOS 来作为平台的名字。要说明额外的特定主版本号则使用类似 iOS 8 这样的名字,你可以明确更小一点的版本号比如 iOS 8.3 和 macOS 10.10.3。
if #available(iOS 10, macOS 10.12, *) {// Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS// 对于iOS平台,只在iOS10及以上版本执行// 对于macOS平台,只在macOS10.12及以上版本执行// 最后的*表示在其他所有平台都执行} else {// Fall back to earlier iOS and macOS APIs}
其他
selector(name)
自定义日志
原始接口
// 打印日志// - items: 打印内容,可变参数// - separator: 打印内容之间的分隔符,默认一个空格// - terminator: 打印内容最后的结束符,默认一个换行符func print(_ items: Any..., separator: String = " ", terminator: String = "\n")
举例说明
print(1, 2, 3, separator: "-", terminator: "\r")1-2-3Program ended with exit code: 0
方法定义
func log(_ message: Any...,file: String = #file, function: String = #function, line: Int = #line) {let fileName = (file as NSString).lastPathComponentlet info = """[FILE]: \(fileName)[FUNC]: \(function)[LINE]: \(line)[MSG]: \(message)"""print(info)}
方法测试
func test() {log(1, 2)}test()
方法扩展
可在自定义日志方法中,添加日期时间信息、是否仅在 DEBUG 模式下开启等功能
