我已经以下代码:强制投,即使协议需要给定类型
import UIKit
protocol Fooable: class where Self: UIViewController {
func foo()
}
class SampleViewController: UIViewController, Fooable {
func foo() {
print("foo")
}
}
let vc1: Fooable = SampleViewController()
let vc2: Fooable = SampleViewController()
// vc1.show(vc2, sender: nil) - error: Value of type 'Fooable' has no member 'show'
// (vc1 as! UIViewController).show(vc2, sender: nil) - error: Cannot convert value of type 'Fooable' to expected argument type 'UIViewController'
(vc1 as! UIViewController).show((vc2 as! UIViewController), sender: nil)
注释行不编译。
为什么我会被迫投协议类型对象UIViewController
即使Fooable
协议要求,这符合它的类型从UIViewController
继承?
是的,它工作,因为'vc1'和'vc2'现在是'SampleViewController'类型。我的帖子显然是简化的例子,例如。考虑这些对象是从函数'func buildVC(vcType:VCTypeEnum) - > Fooable'返回的。你可以发布更多的源代码吗? – zgorawski
@zgorawski?没有更多细节,将很难帮助你。 – jbouaziz
也没有,没有任何类可以实现此协议,请检查:https://ibb.co/ij1Wik – zgorawski