ios - AnyObject 在 Xcode8 beta6 中不工作?

标签 ios swift xcode swift3 xcode8-beta6

在Xcode8 beta6中,以下代码会引起警告:'is' test is always true。但它不会打印通行证。

    struct TestStruct {
    }

    //warning: 'is' test is always true
    if TestStruct() is AnyObject {
        print("pass")
    }

下面的代码将引起警告:从“T”到“AnyObject”的条件转换总是成功

public static func register<T>(_ protocolType: T.Type, observer: T) {

    //Warning: Conditional cast from 'T' to 'AnyObject' always succeeds
    guard let object = observer as? AnyObject else {
        fatalError("expecting reference type but found value type: \(observer)")
    }
    //...
}

最佳答案

警告按预期工作:TestStruct() 的 false 返回是 AnyObject,但是,不是

此答案的先前版本感知到警告,

'is' test is always true

作为错误,并包含一些关于为什么会出现这种感知到的错误警告的讨论。 TestStruct() is AnyObject 在运行时评估为 false,但是,被认为是预期的行为。

鉴于对 bug report filed by the OP (SR-2420) 的评论, 似乎情况是相反的:从 Xcode 8/beta 6 开始,is 测试 should 始终评估为 true,而 bug OP:s post 是 TestStruct() is AnyObject 在运行时评估为 false 的事实。

Joe Groff writes :

This is correct, because everything bridges to AnyObject now.

...

is/as AnyObject always succeed for all types now. It's behaving as intended.


用于将 Swift 值转换为 Obj-C 对象的新 SwiftValue

(有关更多详细信息,请参阅下面评论中的讨论,感谢@MartinR)

似乎没有明确实现的 Swift 值可以通过例如桥接到 Obj-C 对象。符合 _ObjectiveCBridgeable(参见例如 the following Q&A for details regarding _ObjectiveCBridgeable),将自动使用新的 SwiftValue 框以允许转换为 Obj-C 对象。

swift/stdlib/public/runtime/SwiftValue.mm 的初始提交消息阅读:

Runtime: Implement an opaque 'SwiftValue' ObjC class to hold bridged values

If there's no better mapping for a Swift value into an Objective-C object for bridging purposes, we can fall back to boxing the value in a class. This class doesn't have any public interface beyond being NSObject-conforming in Objective-C, but is recognized by the Swift runtime so that it can be dynamically cast back to the boxed type.

关于ios - AnyObject 在 Xcode8 beta6 中不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39033194/

相关文章:

ios - Xcode 10.2 上的 Swift 通用框架问题

Swift4 - 带有文本字段的多个警报 - 完成处理程序

ios - 如何使用原始索引路径从数组中删除对象?

ios - 如何为工作区设置 Jenkins Xcode 插件?

ios - 是否可以在 Ubuntu 上运行 Appium iOS 自动化测试?

ios - SWIFT ALAssetsLibrary 不枚举组

swift - 使用 IBOutlet 连接 MapKit View 时应用程序崩溃

iphone - 通过 App Store 分发 iPad 内部应用程序

ios - 从 [NSString : AnyObject] as UIViewAnimationCurve? 获取对象

ios - 如何让十进制键盘在 iOS 中消失