Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Swift中如何使用 #if DEBUG

Swift暂时还不支持大多数的预处理宏操作,但是可以支持“#if/#else/#endif”语句。下面进行简单的设置使 #if DEBUG 有效,更详细的内容见:http://stackoverflow.com/questions/24003291/ifdef-replacement-in-swift-language
  1. 在项目的Build Settings里配置Swift Compiler - Custom Flags,展开Other Swift Flags,在Debug右侧输入“-DDEBUG”。
    也可以“-D DEBUG”,但是不能有赋值,如:“-DDEBUG=1” 或 “-D DEBUG=1”都是无效的。
  2. 在项目的Build Settings里配置Apple LLVM x.x - Preprocessiong,展开Preprocessor Macros,在Debug右侧默认包含“DEBUG=1”,若没有请手动加入。
说明:第1步使Swift代码编译Debug时定义DEBUG标记,第2步使Objective-C、C、C++的LLVM预处理在Debug时定义DEBUG=1宏标记。如果是纯Swift工程可以忽略第2步。例子:为Swift和Objective-C混合代码工程设置DEBUG和FOO标记根据步骤1,设置如图:根据步骤2,设置如图:现在Swift和Objective-C的代码进行DEBUG和FOO的判断将一致。提示:在代码编辑器中,#if 分支的代码,条件成立的会有代码着色。演示代码:Swift// TestSwift.swiftimport Foundationclass TestSwift {static func printSomething() {print("(__FUNCTION__) in (NSURL(fileURLWithPath:__FILE__).lastPathComponent!)")#if DEBUG && FOOprint("* DEBUG && FOO"#elseif DEBUGprint("* DEBUG")#elseprint("* NO DEBUG")#endif#if !BARprint("* NO BAR")#endif}}演示代码:Objective-C// 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");#elseNSLog("* NO DEBUG");#endif#ifndef BARNSLog(@"* NO BAR");#endif}@end// PROJECTNAME-Bridging-Header.h#import "TestObj.h"
演示代码:打印输出// ViewController.swiftimport UIKitclass ViewController: UIViewController {override func viewDidLoad() {super.viewDidLoad()TestSwift.printSomething()TestObj.printSomething()}}输出结果:printSomething() in TestSwift.swift* DEBUG && FOO* NO BAR2016-03-04 14:50:41.331 test-swift[1187:48511] +[TestObj printSomething] in TestObj.m2016-03-04 14:50:41.332 test-swift[1187:48511] * DEBUG && FOO2016-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到Linux公社资源站下载:------------------------------------------分割线------------------------------------------免费下载地址在 http://linux.linuxidc.com/用户名与密码都是www.linuxidc.com具体下载目录在 /2016年资料/4月/13日/Swift中如何使用 #if DEBUG/下载方法见 http://www.linuxidc.com/Linux/2013-07/87684.htm------------------------------------------分割线------------------------------------------您可用The Unarchiver、p7zip 或者 BetterZip 来解压 7z 文档。本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-04/130164.htm