Disclaimer: I have yet to familiarize myself with Swift 4.. so hopefully this helps.
First, you dont have a subclass of UIViewController that adheres to Cool. So you need to do that. UIViewController, and Cool like you've shown here doesnt provide enough info to suggest that downcasting can be perfomed between the two. Afterwards, you need to update viewcontroller in Class1 as that subclass. You wont be able to cast UIViewController as Cool otherwise with what you're providing here.
Maybe some more context would be helpful, to help with the purpose of Cool
. By this I mean that i do not know what you need Cool
for/what Cool
is for generally in your use-case, but the following gets it all to compile.
public protocol Cool {
init<T: UIViewController>(content: T) where T: Cool
}
class CoolController : UIViewController, Cool {
required init<T>(content: T) where T : UIViewController, T : Cool {
super.init(nibName: nil, bundle: nil)
//Do whatever you need here..?
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class Class1: NSObject, Cool {
var viewController: CoolController?
var cool: Cool?
required init<T>(content: T) where T : UIViewController, T : Cool {
super.init()
if let cont = content as? Cool {
cool = cont
} else if let controller = content as? UIViewController{
viewController = CoolController(content: content)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
// Swift 4 : let viewController: UIViewController & Cool
*/
func atSomePointLater() {
// Ho to get this to compile? ///Optionally.. use a GUARD statement here..
if let c = viewController {
Class2(content: c, someText: nil)
}
}
}
class Class2 {
public init<T: UIViewController>(content: T, someText: String?) where T: Cool {
}
}
Sidenote - Update: I would definitely provide context for Cool, and as to why you're instantiating a UIViewController inside of an object-only class. Not mandatory, but definitely intriguing. Also, I could not use the cool = Cool? variable inside of your atSomePointLater() method because there's no way of knowing that Cool and UIViewController can be downcasted (as I said above).
Stay Cool
.. sorry, i just had to...