1

I am trying to become a better developer and just started to study and use software patterns in small test projects.

In my current project I focused on the builder pattern.

Basically all I have is an App with two Views (Storyboards), A single ViewController-Class (used by all of the views) and one Builder-Class that creates an object with two properties. The Builder-Class is implemented in the ViewController.

    class ViewController: UIViewController {
    @IBOutlet var startTimePicker: UIDatePicker!
    @IBOutlet var workingHoursPicker: UIDatePicker!

    @IBAction func setStartTimeButtonPressed(_ sender: Any) {
        setStartTime()
    }
    
    @IBAction func setWorkingHoursButtonPressed(_ sender: Any) {
        setWorkingHours()
    }
    
    var workdayBuilder: WorkdayBuilder = ConcreteWorkdayBuilder()
    ....

My current problem is that every time I navigate to the next View (using a Segue) the ViewController will be instantiated again and loses the value I set in the previous view.

I know that I could technically just pass the value to the next ViewController and then set it there or that I could set the value and then pass the instance of my builder to the next view. But that would kind of destroy the purpose of the builder in this project IMO.

I then thought that I could wrap my Builder into a Singleton and use it like a shared instance across the views:

    final class WorkdayBuilderSingleton { 
        static let sharedInstance: WorkdayBuilder = ConcreteWorkdayBuilder() 
        init() {} 
    }

But this lead to another error in my VC when I tried to set a property. "Cannot assign to property: 'sharedInstance' is a 'let' constant".

So I am left with some questions and hope you can help me.

Is it a good or OK practice in general to make a builder a singleton or did I make a bad mistake here?

If it is OK, can I change mit static let into a static var or would that kill the singleton?

bkDev
  • 66
  • 5
  • Why would the builder class be a property in your VC in the first place? For me a builder something you create an instance of and then call one or more functions on it to build whatever it is building and then you do something with the result and discard the builder. If you need to build again you simply create a new instance. – Joakim Danielson Nov 15 '22 at 07:50
  • I put it as a property so that I can call it within different Methods of the VC. Action1 is connected to the 1st View. Therefore it needs to call builder.method1. Action2 to the 2nd View. Therefore builder.method2. I wasn't expecting that the VC gets instantiated for each view. Hope that makes sense? – bkDev Nov 15 '22 at 12:03

0 Answers0