#ifdef replacement in the Swift language

前端 未结 17 1727
名媛妹妹
名媛妹妹 2020-11-22 10:35

In C/C++/Objective C you can define a macro using compiler preprocessors. Moreover, you can include/exclude some parts of code using compiler preprocessors.

         


        
17条回答
  •  花落未央
    2020-11-22 11:38

    There is no Swift preprocessor. (For one thing, arbitrary code substitution breaks type- and memory-safety.)

    Swift does include build-time configuration options, though, so you can conditionally include code for certain platforms or build styles or in response to flags you define with -D compiler args. Unlike with C, though, a conditionally compiled section of your code must be syntactically complete. There's a section about this in Using Swift With Cocoa and Objective-C.

    For example:

    #if os(iOS)
        let color = UIColor.redColor()
    #else
        let color = NSColor.redColor()
    #endif
    

提交回复
热议问题