【发布时间】:2017-02-03 22:03:28
【问题描述】:
仅供参考:这里提出了 Swift 错误:https://bugs.swift.org/browse/SR-3871
我遇到了一个奇怪的问题,即强制转换不起作用,但控制台将其显示为正确的类型。
我有一个公共协议
public protocol MyProtocol { }
我在一个模块中实现它,使用一个返回实例的公共方法。
internal struct MyStruct: MyProtocol { }
public func make() -> MyProtocol { return MyStruct() }
然后,在我的视图控制器中,我触发了一个以该对象作为发送者的 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 时,它给了我错误Could not cast value of type '_SwiftValue' (0x1107c4c70) to 'MyProtocol' (0x1107c51c8)。但是,po sender 将输出一个有效的 Module.MyStruct 实例。
为什么这个演员表不起作用?
(我已经设法通过将我的协议封装在一个结构中来解决它,但我想知道它为什么不能按原样工作,以及是否有更好的方法来解决它)
【问题讨论】:
-
这里只是一时兴起,但是将这里的内部声明
internal struct MyStruct: MyProtocol { }更改为public有什么改变吗? -
@Dennis Nope :(