I have the following code in my UIViewController subclass
class SideMenu: UIViewController {
var contentViewController: UIViewController?
override func shouldAutorotate() -> Bool {
return contentViewController?.shouldAutorotate()
}
}
But for some reason I get the following error:
Value of optional type 'Bool?' not unwrapped; did you mean to use '!' or '??'
I would expect that the optional chaining unwraps the optional, but this dosen't seem to be true? Am I wrong?
The result of an optional chain is optional. So ?.shouldAutorotate()
yields a Bool?
while your function expects a Bool
. Hence the error:
Value of optional type 'Bool?' not unwrapped; did you mean to use '!' or '??'
There are two possible solutions outlined by the error. One is to unwrap either with contentViewController!.shouldAutorotate()
or contentViewController?.shouldAutorotate()!
but both of these will crash if contentViewController
was nil
and that's not what you had in mind.
The other option is to provide a fallback value in case your Bool?
is nil
. There's a nice operator for chaining: ??
which takes T?
on the lefthand side and T
on the righthand side.
That is, if you want to return false when contentViewController is nil you would return the following:
return contentViewController?.shouldAutorotate() ?? false
This is effectively the same behavior as the following code:
if let controller = contentViewController {
return controller.shouldAutorotate()
} else {
return false
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments