記錄從Objective-C轉向Swift過程中的一些高級用法
1.預處理宏
C/C++/Objective-C中可以這樣使用
#define a b
由于Swift沒有預處理啦膜,正如Apple文檔中所說:
The Swift compiler does not include a preprocessor.
Swift采用了一些方式來替代宏:
- 簡單的宏
Where you typically used the #define
directive to define a primitive constant in C and Objective-C, in Swift you use a global constant instead.
對于C或者OC中用來定義常量的宏,在Swift中可以使用全局的常量來代替淌喻。
- 復雜的宏
Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.
在Swift中并沒有東西可以用來替代C和OC中復雜的宏僧家。復雜的宏雖然在編寫代碼的時候有一些作用,但是在debug和重構的時候會造成一些困難裸删。Swift中可以使用函數和泛型來不加任何妥協(xié)的實現相同的結果八拱。因此,OC和C中的復雜的宏在Swift中無法使用涯塔。
- 構建配置
Swift是根據構建配置來進行條件編譯的肌稻。
在需要區(qū)分開發(fā)還是發(fā)布版本的時候,OC這樣做
#ifdef DEBUG
#else
#endif
但是在swift中沒有DEBUG這個宏匕荸,如果要實現相同的需求爹谭,有兩個方法:
- 添加OC類來協(xié)助實現
.h文件中:extern BOOL const DEBUG_BUILD;
.m文件中:
#ifdef DEBUG
BOOL const DEBUG_BUILD = YES;
#else
BOOL const DEBUG_BUILD = NO;
#endif
之后在xxx-Bridging-Header.h文件中#import "Preprocessor.h"
,然后新建tool.swift
func printDuringDebug(items: Any...) {
if DEBUG_BUILD {
debugPrint(items)
}
}
使用的時候printDuringDebug("hello world")
- Build Settings搜索“Custom Flags”榛搔,然后"Other Swift Flags"诺凡,在debug下添加-DDEBUG东揣、release下添加-DRELEASE。
有錯誤歡迎指出腹泌,有問題歡迎提問嘶卧。