- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
仅供引用:此处引发的 Swift 错误:https://bugs.swift.org/browse/SR-3871
<小时/>我遇到一个奇怪的问题,强制转换不起作用,但控制台将其显示为正确的类型。
我有一个公共(public)协议(protocol)
public protocol MyProtocol { }
我在一个模块中实现了这个,并使用返回实例的公共(public)方法。
internal struct MyStruct: MyProtocol { }
public func make() -> MyProtocol { return MyStruct() }
然后,在我的 View Controller 中,我触发一个以该对象作为发送者的 Segue
let myStruct = make()
self.performSegue(withIdentifier: "Bob", sender: myStruct)
到目前为止一切都很好。
问题出在我的 prepare(for:sender:)
方法中。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Bob" {
if let instance = sender as? MyProtocol {
print("Yay")
}
}
}
但是,实例到 MyProtocol 的转换始终返回 nil
。
当我运行 po sender as! MyProtocol
在控制台中,它给我错误无法将类型“_SwiftValue”(0x1107c4c70) 的值转换为“MyProtocol”(0x1107c51c8)
。但是,po sender
将输出有效的 Module.MyStruct
实例。
为什么这个 Actor 阵容不起作用?
(我已经通过将协议(protocol)封装在结构中来解决这个问题,但我想知道为什么它不能按原样工作,以及是否有更好的方法来修复它)
最佳答案
这是一个非常奇怪的错误 - 看起来它是在一个实例通过装箱在 _SwiftValue
中桥接到 Obj-C 并静态类型为 Any(?)< 时发生的。/
。然后,该实例无法转换为它所遵循的给定协议(protocol)。
根据 Joe Groff 在 bug report you filed 的评论中的说法:
This is an instance of the general "runtime dynamic casting doesn't bridge if necessary to bridge to a protocol" bug. Since sender is seen as
_SwiftValue
object type, and we're trying to get to a protocol it doesn't conform to, we give up without also trying the bridged type.
一个更简单的例子是:
protocol P {}
struct S : P {}
let s = S()
let val : Any = s as AnyObject // bridge to Obj-C as a _SwiftValue.
print(val as? P) // nil
奇怪的是,首先转换为 AnyObject
然后转换为协议(protocol)似乎有效:
print(val as AnyObject as! P) // S()
因此,将其静态键入为 AnyObject
会使 Swift 还检查桥接类型的协议(protocol)一致性,从而使转换成功。正如 Joe Groff 在另一条评论中所解释的,其原因是:
The runtime has had a number of bugs where it only attempts certain conversions to one level of depth, but not after performing other conversions (so AnyObject -> bridge -> Protocol might work, but Any -> AnyObject -> bridge -> Protocol doesn't). It ought to work, at any rate.
关于swift - Any 中的 Swift 转换失败?协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47291158/
我是一名优秀的程序员,十分优秀!