Swift中如何使用 #if DEBUG

Swift暫時還不支持大多數的預處理宏操做,可是能夠支持「#if/#else/#endif」語句。swift

下面進行簡單的設置使 #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步。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 文檔。