I’ve recently started with dependancy injections in swift and i cant figure out how to pass a custom class while segueing to another Viewcontroller.
class Content {
var title:String
var about:String
var location:String
init(data: [String: Any]) {
self.title = data["title"] as? String ?? ""
self.about = data["about"] as? String ?? ""
self.location = data["location"] as? String ?? ""
}
}
First Viewcontroller – Performing segue and passing necessary data.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "NextView", sender: self.allcontent[indexPath.item])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "NextView" {
let vc = segue.destination as! NextViewController
let selectedRow = sender as? Content
vc.content = selectedRow!
}
}
Attempting to initiate NextViewcontroller with the passed custom class from the first ViewController.
class NextViewController: UIViewController {
var content: Content
init(content: Content) {
self.content = content
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// this way i can access properties from the custom class directly
//content.title
//content.about
}
I keep getting different warnings as i’m not sure on how to structure this correctly.
- ‘super.init’ isn’t called on all paths before returning from initializer
- ‘required’ initializer ‘init(coder:)’ must be provided by subclass of ‘UIViewController’
I’ve seen below code implemented in an example but i don’t understand what “coder” is or how its supposed to be used.
class EditUserViewController: UIViewController {
var selectedUser: User
init?(coder: NSCoder, selectedUser: User) {
self.selectedUser = selectedUser
super.init(coder: coder)
}
required init?(coder: NSCoder) {
fatalError("You must create this view controller with a user.")
}
// ...
}
Any help or example would be appreciated.