在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
的事实。
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/