Application scenarios

Write code in the project, but need to differentiate some functions (system, equipment, etc.). Need to use the system of conditional compilation to deal with.

API and language

Swift

Core logic/code

This is mainly achieved by #if xx #elseif XXX #else xx #endif conditional compilation code. In the condition, xx needs to use those already defined by the system.

Project Settings for conditional compilation

You can set the conditional compilation flag in the Active Compilation Conditions option under target -> Bulid Settings -> Swift Compiler-custom Flage. DEBUG or custom TEST. You can also add Flags under Other Swift Flags (you need to add -d before the Flags)

System Version Detection

Check the system version with if #available(*,*,*){} code condition, if true, perform the operation

API availability instructions

Classes, structs, functions, etc., set system limits, or are not available, etc. Xcode will prompt you when called. The core code is to use the @available() code.

The sample code

Set condition code

/ / operating system: macOS/iOS/tvOS/watchOS/Linux/Android/Windows/FreeBSD
#if os(macOS) || os(iOS)
// CPU architecture: i386\x86_64\arm\arm64
#elseif arch(x86_64) || arch(arm64)
/ / swift version
#elseif swift(<5) && swift(> =3)
/ / simulator
#elseif targetEnvironment(simulator)
// You can import a module
#elseif canImport(Foundation)
#else
#endif
Copy the code

System Version Detection

if #available(iOS 10.macOS 10.12.*) {
    // For iOS, perform this operation only on iOS10 or later
    // For macOS platforms, only macOS 10.12 and later
    // The last * flag is implemented on all other platforms
}
Copy the code

API availability instructions


Run only on iOS 10 or macOS 10.15 or later
@available(iOS 10.macOS 10.15.*)
class Person {}

struct Student {
    // study_ method not available, use study
    @available(*, unavailable, renamed: "study")
    func study_(a) {}
    func study(a) {}
    
    The run function cannot be used on iOS 11 or macOS 10.12 or later
    @available(iOS, deprecated: 11)
    @available(macOS, deprecated: 10.12)
    func run(a){}}Copy the code