ios - Optional Chaining Not Working As Expected -
i have next code in uiviewcontroller subclass
class sidemenu: uiviewcontroller { var contentviewcontroller: uiviewcontroller? override func shouldautorotate() -> bool { homecoming contentviewcontroller?.shouldautorotate() } } but reason next error:
value of optional type 'bool?' not unwrapped; did mean utilize '!' or '??'
i expect optional chaining unwraps optional, dosen't seem true? wrong?
the result of optional chain optional. ?.shouldautorotate() yields bool? while function expects bool. hence error:
value of optional type 'bool?' not unwrapped; did mean utilize '!' or '??'
there 2 possible solutions outlined error. 1 disclose either contentviewcontroller!.shouldautorotate() or contentviewcontroller?.shouldautorotate()! both of these crash if contentviewcontroller nil , that's not had in mind.
the other alternative provide fallback value in case bool? nil. there's nice operator chaining: ?? takes t? on lefthand side , t on righthand side.
that is, if want homecoming false when contentviewcontroller nil homecoming following:
return contentviewcontroller?.shouldautorotate() ?? false this same behavior next code:
if allow controller = contentviewcontroller { homecoming controller.shouldautorotate() } else { homecoming false } ios swift
No comments:
Post a Comment