如何在Swift中进行弱链接? [英] How do I do weak linking in Swift?

查看:140
本文介绍了如何在Swift中进行弱链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,如果我想使用仅出现在新版iOS中的特定类,我会这样做:

In Objective-C, if I wanted to use a specific class that's only present in a new version of iOS, I would do something like this:

if( [UIBlurEffect class] ) {
  // do something with UIBlurEffect
}
else {
  // gracefully fallback to old behavior
}

然而,相当于Swift:

However, the equivalent Swift:

if UIBlurEffect.self != nil {
  let blur: UIBlurEffect = UIBlurEffect(...)
  // ...
else {
  // ...
}

// also occurs with NSClassFromString("UIBlurEffect")

没有相同的功能。

如果在 NSNewFeature 可用,一切都很好。但是如果未定义类,则在启动应用程序时出现链接错误:

If run on an environment where NSNewFeature is available, everything is fine. But if the class isn't defined, I get a link error when starting the application:

dyld: Symbol not found: _OBJC_CLASS_$_UIBlurEffect

那么如何在Swift中进行弱链接?

So how do I do weak linking in Swift?

编辑已添加 UIBlurEffect 作为具体示例。

Edit Added UIBlurEffect as specific example.

推荐答案

好像我已经知道你能做什么

Seems like I've figured out what you can do


  1. 我使用 NSClassFromString()来检查设备上是否有类,即

  1. I used NSClassFromString() to check if class is available on device, i.e.

if NSClassFromString("UIBlurEffect") {
    let blur = UIBlurEffect(...)
    //...
}
else {
    //...
}


  • 需要使 UIKit.framework (或其他相应的框架)可选。如果您在XCode6-BetaX中创建基于Swift的应用程序,则所有框架都不会显式添加到链接构建阶段,因此您需要转到目标设置,添加 UIKit.framework 作为链接框架(在'Link Binary With Libraries'部分中)并将其状态更改为 Optional 这一步可以解决问题,我已经设法运行版本特定的代码而没有问题。

  • It's needed to make UIKit.framework (or another corresponding framework) optional. If you create Swift-based application in XCode6-BetaX, all the frameworks wouldn't be explicitly added to the link build phase so you need to go to your target settings, add UIKit.framework as a linked framework (in 'Link Binary With Libraries' section) and to change its status to Optional. This step does the trick and I've managed to run version specific code without a problem.

    更新:您不再需要将其设为可选项,因为Xcode 6 beta 6(来自@ user102008)

    Update: You don't need to make it optional anymore, since Xcode 6 beta 6 (via @user102008)

    Update 2 :您实际上无法对nil执行隐式if语句检查(自Xcode 6 Beta 5起)。你需要断言它:

    Update 2: You can't actually perform implicit if statement checks for nil (since Xcode 6 Beta 5). You need to assert it like that:

        if NSClassFromString("UIBlurEffect") != nil {
            let blur = UIBlurEffect(...)
            //...
        }
        else {
            //...
        }
    

    (来自@ daniel-galasko)

    (via @daniel-galasko)

    这篇关于如何在Swift中进行弱链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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