Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Imports in Swift

I have a Log function I use in various apps. Its convenient for this to also make Crashlytics logging calls since I use it throughout the app.

However, not every app uses Crashlytics. In Objective C you could handle this with preprocessor conditions.

How would one handle this in code? I think there are ways to make the function conditional perhaps. But how would I optionally or weak import Crashlytics?

import Foundation
//import Crashlytics

/// Debug Log: Log useful information while automatically hiding after release.
func DLog<T>(message: T, filename: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) {
//    CLSLogv("\(NSString(string: filename).lastPathComponent).\(function) line \(line) $ \(message)", getVaList([]))
    print("[\(NSString(string: filename).lastPathComponent) \(function) L\(line)] \(message)")
}
like image 998
Ryan Poolos Avatar asked Oct 01 '15 22:10

Ryan Poolos


1 Answers

You can do this now in Swift 4.1 with the new canImport() directive. This is the Swift Evolution proposal that describes how it works: https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md

So you could do:

#if canImport(Crashlytics)
func dLog() { 
    // use Crashlytics symbols 
}
#endif
like image 137
Javier Soto Avatar answered Sep 29 '22 12:09

Javier Soto