Rappe Stegarn Rappe Stegarn - 5 months ago 9
Swift Question

Check which ViewController made a segue (from the destination ViewController)

I have a code that gives random segues to my 12 ViewControllers.

In ViewController1 it looks like this;

let segues = ["1-2", "1-3", "1-4", "1-5", "1-6", "1-7", "1-8", "1-9", "1-10", "1-11", "1-12"]
let index = Int(arc4random_uniform(UInt32(segues.count)))
let segueName = segues[index]
self.performSegueWithIdentifier(segueName, sender: self)


And in ViewController 2 it looks the same, but the segue names change to;

let segues = ["2-1", "2-3", "2-4", "2-5", "2-6", "2-7", "2-8", "2-9", "2-10", "2-11", "2-12"]


(The
"1"
changes into a
"2"
) - and so forth for all 12 ViewControllers.

.

Now, what I want to do is delete the ViewControllers that has already been shown, so that the next segue won't go back to any of the previous ViewControllers.

Example:

• ViewController1 makes a segue to ViewController2 (
"1-2"
)

• ViewController2 deletes the segue
"2-1"
from the array
segues


• ViewController2 then makes a segue to ViewController3
"1-3"


• ViewController3 deletes the segue
"3-1"
and
"3-2"


and so on...

Answer

Here is one way to do it:

  1. Keep an array of the viewControllers you have visited as a property in each of your viewControllers. Let's call this visited. Also, create a protocol called TracksVisited that all of your viewControllers will adopt:

    protocol TracksVisited {
        var visited: [Int] { get set }
    }
    
    class ViewController1: UIViewController, TracksVisited {
        var visited = [Int]()
    
        ...
    }
    
    class ViewController2: UIViewController, TracksVisited {
        var visited = [Int]()
    
        ...
    }
    
  2. Add the current viewController number to this list:

    let vc = 3  // current viewController
    visited.append(vc)
    
  3. Generate the list of segues and choose one:

    // generate list of all viewControllers
    let all = Array(1...12)
    
    // remove visited from all
    let rest = all.filter { !visited.contains($0) }
    
    // create list of segues
    let segues = rest.map { "\(vc)-\($0)" }
    
    // choose random segue and go there
    let index = Int(arc4random_uniform(UInt32(segues.count)))
    let segueName = segues[index]
    self.performSegueWithIdentifier(segueName, sender: self)
    
  4. In prepareForSegue, pass the list of visited to the destination viewController:

    if let destinationViewController = segue.destinationViewController as? TracksVisited {
        destinationViewController.visited = visited
    }