edey
edey

Reputation: 159

Send array from 1 view controller to 2 other separate view controllers

I have an array in one view controller that I want to send to two other view controllers - i am doing it via a prepareForSegue:

var userId = ""

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let FollowersUsersViewController = segue.destination as! FollowersUsersViewController
    FollowersUsersViewController.followersUserId = userId

    let FollowingUsersViewController = segue.destination as! FollowingUsersViewController
    FollowingUsersViewController.followingUserId = userId
}

For the other 2 view controllers I am calling the array like so:

View controller 1:

var followersUserId = String() 
let followersProfileId = followersUserId

View controller 2:

var followingUserId = String() 
let followingProfileId = followingUserId

It seems to work when i send it to one of the view controllers (and comment out the other) but then only one of the buttons work when i run the app. When I do it for both view controllers (as above) i get a Thread 1: signal SIGABRT error - how can it work for both?

Appreciate any help :)

Upvotes: 0

Views: 60

Answers (2)

Atila Costa
Atila Costa

Reputation: 11

One thing you could do to improve this code is to make both VC's conform to a protocol that enforces this variable's presence:


protocol UserIdController {
    var userId: UUID { get set }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let viewController = segue.destination as? UserIdController {
            viewController.userId = userId
    }
}

It would be less descriptive but much more elegant and swift-like.

Upvotes: 1

Johnykutty
Johnykutty

Reputation: 12859

This is crashing because you are trying to cast wrong view controller. Thats is in a single iteration the segue.destination either FollowersUsersViewController or FollowingUsersViewController.

You have conditionally cast it before use.
Try this code

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let controller = segue.destination as? FollowersUsersViewController {
        controller.followingUserId = userId
    } else if let controller = segue.destination as? FollowingUsersViewController {
        controller.followingUserId = userId
    }
}

Upvotes: 3

Related Questions