[Solved] I do not understand what this code does(the code is about segues)


That’s not the best segue code. Here’s how I’d code it (for the record, there are several ways to code this):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "[segue name here]" {
        if let nextVC = segue.destination as? CreateTasksViewController {
            nextVC.tasksVC = self
        }
    }
}

The code you posted has what is called a “forced unwrap” of the segue destination (that’s the as! you asked about). Here’s a question with a pretty good answer explaining the dangers of forced unwrapping. Scroll down to the divider in the answer.

While I’m sure the code compiles (and likely runs), the problem is code maintenance.

Suppose you have several segues defined between several scenes, each with their own view controller? My code, as matter of style, gives up a bit of “Swiftiness” for “explicitness”:

  • (1) A check is made that the segue is the correct one
  • (2) An if let… as? is made to safely check if the segue destination if the correct view controller
  • (3) If everything passes the checks, then the code is executed. In this case, it looks like it passes the entire(!) view controller into a variable called tasksVC in the CreateTasksViewController.

I’m actually cautious about item 3 – why would anyone pass one view controller into another one as a variable? Most cases in prepare(for segue:) one or more variables inside the sending VC are passed to the destination. If I may offer this to you… find another tutorial!

solved I do not understand what this code does(the code is about segues)