sckring
sckring

Reputation: 31

Error message Could not cast value type error - Swift

Recently I added the below code in order to get some user entered data to appear when the edit button was tapped. But instead of opening the edit view controller, the app freezes.

 override func tableView(_ tableView: UITableView,
               leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?

{

    let modifyAction = UIContextualAction(style: .normal, title:  "Edit", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
        print("Update action ...")

        let MainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        let vc = MainStoryboard.instantiateViewController(withIdentifier: "FreshReleaseEdit") as! EditfreshreleaseViewController
        vc.selectedFreshRelease = self.freshreleases[indexPath.row]
        self.present(vc, animated: true, completion: nil)
        success(true)



    })
    modifyAction.title = "Edit"
    modifyAction.backgroundColor = .blue



    return UISwipeActionsConfiguration(actions: [modifyAction])
    }

When I tap the edit button, the app crashes with the below error message:

Update action ... Could not cast value of type 'UINavigationController' (0x1d37e81e0) to 'fresh_release.EditfreshreleaseViewController' (0x1043d7248). 2018-12-17 20:56:30.547305-0500 fresh release[7644:1985252] Could not cast value of type 'UINavigationController' (0x1d37e81e0) to 'fresh_release.EditfreshreleaseViewController' (0x1043d7248). (lldb)

Any suggestions on how to fix this?

Upvotes: 1

Views: 54

Answers (1)

Sweeper
Sweeper

Reputation: 271515

It is likely that your EditfreshreleaseViewController is embedded in a UINavigationController. That is why your cast didn't work.

You need to first cast the VC to UINavigationController, then cast the topViewController to EditfreshreleaseViewController.

Change the line:

let vc = MainStoryboard.instantiateViewController(withIdentifier: "FreshReleaseEdit") as! EditfreshreleaseViewController

to

let navVC = MainStoryboard.instantiateViewController(withIdentifier: "FreshReleaseEdit") as! UINavigationController
let vc = navVC.topViewController as! EditfreshreleaseViewController

Upvotes: 1

Related Questions