Monday, July 4, 2022
HomeiOS Developmentios - Make variable knowledge kind settle for all UIViewController subclass

ios – Make variable knowledge kind settle for all UIViewController subclass


So I’ve many buttons, possibly as much as 12, which is populated from a ForEach loop. And when each is clicked, the button index will probably be handed as parameter to a operate which is able to current a brand new ViewController based mostly on the index of the button.

ForEach(0...11, id: .self){ index in
    Button {
        openController(index: index)
    }, label: {
        Textual content("Button (index)")
    }
}

Now in my openController operate, I need to make my code as brief as attainable. So I’ll make a swap assertion to find out the button clicked and open the respective viewcontroller.

So here is the place my query is available in… I need to create only one variable which will probably be initialized by the respective Viewcontroller. However the issue comes after I declare the variable and attempt to initialize it.

As an illustration, since all of the ViewControllers are subclasses of the UIViewController, I attempted to declare the variable with a UIViewController knowledge kind earlier than initializing it

func openController(index: Int){
    var viewController: UIViewController // declaring the variable
    swap index {
        case 0:
            viewController = ZeroViewController
        case 1:
            viewController = OneViewController
        // And it retains happening until case 11
    }
    self.current(viewController, animated: true)
}

However I will probably be getting errors if I do this saying that I can not convert viewController which is of UIViewController kind to ZeroViewController

So it will make my code cumbersome, as a result of I will must create a variable for each Viewcontroller and in addition current it otherwise making my code appear to be this

func openController(index: Int){
    swap index {
        case 0:
            let viewController = ZeroViewController
            self.current(viewController, animated: true)
        case 1:
            let viewController = OneViewController
            self.current(viewController, animated: true)
        // And it retains happening until case 11
    }
}

So is that the one choice or is there a means I can shorten my code to appear to be the primary operate?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments