How to write logic in Swift,

There is an object in my first controller, for example the string "Hello" .

I need to go to the new controller, immediately register the data in it, from the previous controller string "Hello" .

In the new controller, change this string parameter for example to string "New Hello" .

After that, return to the old controller and update the original line there.

p / s In objective c, it could easily be implemented in blocks, theoretically in Swift it could be done with the same coolants, but can there be any more correct way?

p / s storyboard in the application is not used. Implementation through xib.

    1 answer 1

    When using segue , it will look like this:

     class VC1: UIViewController { // MARK: - Private Instance Attributes private var stringAttr: String? = "Hello" // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else { return } switch identifier { case "GoToVC2": guard let viewController = segue.destination as? VC2 else { break } viewController.stringAttr = stringAttr viewController.stringAttrChangedClosure = { [weak self] (newString) in guard let strongSelf = self else { return } strongSelf.stringAttr = newString } default: break } } } class VC2: UIViewController { // MARK: - Public Instance Attributes var stringAttr: String? = "Hello" { didSet { stringAttrChangedClosure?(stringAttr) } } var stringAttrChangedClosure: ((_ newString: String?) -> Void)? } 

    I want to note that in prepare(for:segue) it is impossible to access form elements (IBOutlet), since at this moment they have not yet been initialized, therefore, it will be necessary to create a temporary variable for storing data ( stringAttr in this example). Those. the string 'viewController.someLabel.test = stringAttr' will cause an execution error, in the event that someLabel is @IBOutlet .

    Also, to change the data in the "transmitting" side (VC1) in the example, it is always necessary to use "blocks".

    • I apologize for not writing, I do not use storyboard. - Victor Mishustin
    • In this case, instead of prepare(for segue: use the function in which the new controller is created and displayed. - Vasilii Muravev