Swift暂时还不支持大多数的预处理宏操做,可是能够支持“#if/#else/#endif”语句。swift
下面进行简单的设置使 #if DEBUG 有效,更详细的内容见:http://stackoverflow.com/questions/24003291/ifdef-replacement-in-swift-language编辑器
说明:第1步使Swift代码编译Debug时定义DEBUG标记,第2步使Objective-C、C、C++的LLVM预处理在Debug时定义DEBUG=1宏标记。若是是纯Swift工程能够忽略第2步。ide
例子:为Swift和Objective-C混合代码工程设置DEBUG和FOO标记函数
根据步骤1,设置如图:优化
根据步骤2,设置如图:ui
如今Swift和Objective-C的代码进行DEBUG和FOO的判断将一致。this
提示:在代码编辑器中,#if 分支的代码,条件成立的会有代码着色。spa
演示代码:Swiftcode
// TestSwift.swift import Foundation class TestSwift { static func printSomething() { print("\(__FUNCTION__) in \(NSURL(fileURLWithPath:__FILE__).lastPathComponent!)") #if DEBUG && FOO print("* DEBUG && FOO") #elseif DEBUG print("* DEBUG") #else print("* NO DEBUG") #endif #if !BAR print("* NO BAR") #endif } }
演示代码:Objective-Cblog
// TestObj.h #import <Foundation/Foundation.h> @interface TestObj : NSObject + (void)printSomething; @end // TestObj.m #import "TestObj.h" @implementation TestObj + (void)printSomething { NSLog(@"%s in %@", __PRETTY_FUNCTION__, [[NSString stringWithCString:__FILE__ encoding:NSUTF8StringEncoding] lastPathComponent]); #if (defined DEBUG) && (defined FOO) NSLog(@"* DEBUG && FOO"); #elif (defined DEBUG) NSLog(@"* DEBUG"); #else NSLog("* NO DEBUG"); #endif #ifndef BAR NSLog(@"* NO BAR"); #endif } @end // PROJECTNAME-Bridging-Header.h #import "TestObj.h"
演示代码:打印输出
// ViewController.swift import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() TestSwift.printSomething() TestObj.printSomething() } }
输出结果:
printSomething() in TestSwift.swift * DEBUG && FOO * NO BAR 2016-03-04 14:50:41.331 test-swift[1187:48511] +[TestObj printSomething] in TestObj.m 2016-03-04 14:50:41.332 test-swift[1187:48511] * DEBUG && FOO 2016-03-04 14:50:41.332 test-swift[1187:48511] * NO BAR
--
在Swfit有另一种方法是经过函数判断编译的优化选项,可是不够直观并且没有官方的文档,不建议使用。
如:
// ** Be carefull, Don`t do this: ** if _isDebugAssertConfiguration() { print("--DEBUG--") }
还有其余两个函数,详细见前面的stackoverflow连接。
--
下载演示代码:test_swift_if_DEBUG.7z
您可用The Unarchiver、p7zip 或者 BetterZip 来解压 7z 文档。