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.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-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");
#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 文档。

posted @ 2016-03-03 11:00  Bob-wei  阅读(22991)  评论(0编辑  收藏  举报