Swift中的条件导入 [英] Conditional Imports in Swift

查看:155
本文介绍了Swift中的条件导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有在各种应用程序中使用的日志功能.由于在整个应用程序中都使用它,因此也方便进行Crashlytics日志记录调用.

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.

但是,并非每个应用程序都使用Crashlytics.在Objective C中,您可以使用预处理程序条件来解决这个问题.

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

一个人如何用代码来处理呢?我认为有一些方法可以使功能成为条件.但是,我将如何选择性地或弱势地导入Crashlytics?

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)")
}

推荐答案

您现在可以在Swift 4.1中使用新的canImport()指令执行此操作.这是Swift Evolution提案,描述了其工作方式: https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md

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

所以您可以这样做:

#if canImport(Crashlytics)
func dLog() { 
    // use Crashlytics symbols 
}
#endif

这篇关于Swift中的条件导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆