swift - How to use optional binding in switch statement in prepare(segue:) -
in swift can use cool feature of switch statement in prepare(segue:) create cases based on type of destination view controller:
example:
override func prepare(for segue: uistoryboardsegue, sender: any?) { switch segue.destination { case let detailviewcontroller detailviewcontroller: detailviewcontroller.title = "detailviewcontroller" } case let otherviewcontroller otherviewcontroller: otherviewcontroller.title = "otherviewcontroller" } } however, if segue triggered split view controller, destination navigation controller, , want switch on class of navigation controller's top view controller?
i want this:
case let nav uinavigationcontroller, let detailviewcontroller = nav.topviewcontroller as? detailviewcontroller: //case code goes here where have same construct use in multiple part if let optional binding.
that doesn't work. instead, have rather painful construct this:
case let nav uinavigationcontroller nav.topviewcontroller detailviewcontroller: guard let detailviewcontroller = nav.topviewcontroller as? detailviewcontroller else { break } detailviewcontroller.title = "detailviewcontroller" that works, seems needlessly verbose, , obscures intent. there way use multi-part optional binding in case of switch statment in swift 3?
i don't think there way switch , case, can closer looking if , case (update: hamish pointed out, case isn't needed scenario) or normal if let:
override func prepare(for segue: uistoryboardsegue, sender: any?) { if let nav = segue.destination as? uinavigationcontroller, let detailviewcontroller = nav.topviewcontroller as? detailviewcontroller { detailviewcontroller.title = "detailviewcontroller" } if let otherviewcontroller? = segue.destination as? otherviewcontroller { otherviewcontroller.title = "otherviewcontroller" } } since switch statement in example isn't going ever verified compiler handling cases (because need create default case), there no added benefit using switch instead of if let
Comments
Post a Comment