I am watching an iOS course video and the person in the course types up this code:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let nextVC = segue.destination as! CreateTasksViewController
nextVC.tasksVC = self
}
The CreateTasksViewController is the view in the project that we are supposed to segue to. Also the "tasksVC" is the current view controller that in the app we are supposed to be on.I do not understand what this code mean and it would be helpful if someone could explain exactly what the function of the code is. Also what is "as!"?If you need any more details regarding my problem, feel free to ask in the comments.
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":
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!