Lena Bru Lena Bru - 1 month ago 9
Objective-C Question

Cannot downcast from 'UIViewController' to a more optional type 'SubclassOfUIViewController<NSString>'

I have a Subclass of UIViewController that is defined as follows

@interface SubclassOfViewController<__covariant Type> : UIViewController
@end
@implementation SubclassOfViewController @end


I am sending this subclass as a segue from screen change.

Now in prepareForSegue I am trying to do the following

public override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "embeddedScroll"){
if let vc = segue.destinationViewController as? SubclassOfViewController<NSString>!{
vc.dataSource = genericDataSource
}

}
}


And receiving the following message:

Cannot downcast from 'UIViewController' to a more optional type 'SubclassOfViewController<NSString>!'


putting question marks instead of exclamation marks does not help.

How can I fix it?

Answer

You usually do not use Optional types for as? casting.

Try just removing that !.

    if let vc = segue.destinationViewController as? SubclassOfViewController<NSString> {