Last active
January 18, 2023 22:01
-
-
Save arkilis/8c5f8c26eae1087ec65a45e5cd512091 to your computer and use it in GitHub Desktop.
Swift compiler directives examples from source: https://needone.app/compiler-directives-in-swift/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
For explanation please go to the post: https://needone.app/compiler-directives-in-swift/ | |
*/ | |
// Environment Checking | |
var url = "" | |
#if DEBUG | |
// use localhost while under debug mode | |
url = "https://localhost" | |
#else | |
// use production url while under release | |
url = "production url" | |
#endif | |
// You can also negate the flag | |
#if !RELEASE | |
// use localhost while under debug mode | |
url = "https://localhost" | |
#else | |
// use production url while under release | |
url = "production url" | |
#endif | |
// Platform Detection | |
#if os(OSX) | |
// compiles for OS X | |
#elseif os(iOS) | |
// compiles for iOS | |
#elseif os(tvOS) | |
// compiles for TV OS | |
#elseif os(watchOS) | |
// compiles for Apple watch | |
#endif | |
// Warnings and Errors | |
#warning("Needs improve on the performance") | |
#error("Needs remove the duplicated code") | |
import Foundation | |
class MyClass { | |
// Some code here | |
#warning("This is a warning message") | |
var myVariable: Int = 0 | |
// Some more code here | |
} | |
// Language version Check | |
// Check the Swift version | |
#if swift(<5) | |
#endif | |
// Check environments like Simulator or Catalyst | |
#if targetEnvironment(simulator) | |
#endif | |
// Module check | |
// Check if a module presents | |
#if canImport(UIKit) | |
#endif | |
// iOS Version Check | |
if #available(iOS 10.0, *) { | |
} | |
@available(iOS 10, macOS 10.15, *) | |
func newMethod() { | |
// this method will be only available when iOS > 10, macOS > 10.15 | |
} | |
// #function, #line and #file | |
import UIKit | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
print(#file, #line, #function) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment