How can i segue a custom class to another Viewcontroller in Swift Properly?
I’ve coded in javascript for a while and i’m struggling to understand what the best practice is.
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 ?? ""
}
}
OBS! Im currently segueing this way which is extremely verbal. If something changes or if there is a typo an error will happen.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "NextView" {
let vc = segue.destination as? NextViewController
let selectedRow = sender as! Content
vc?.title = selectedRow.title
vc?.about = selectedRow.about
vc?.location = selectedRow.location
vc?.value1 = selectedRow.value1
vc?.value2 = selectedRow.value2
vc?.value3 = selectedRow.value3
vc?.value4 = selectedRow.value4
vc?.value5 = selectedRow.value5
vc?.value6 = selectedRow.value6
vc?.value7 = selectedRow.value7
vc?.value8 = selectedRow.value8
}
}
This would be my preferred way but i’m not sure how to do this properly
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!
}
}
class NextViewController: UIViewController {
//Initializing class that has not recieved values yet requires me to have a default value for all.
//This could be many values and complicated ones. Is this unavoidable or do I have to create a class with empty values on all ViewControllers i want to segue a class to?
var content: Content()
//Is it possible and desirable to decontruct values for easy access?
let { title, about, location, view1, view2, view3... } = content
//Or should values be used by accessing class directly
if content.title == "Main Content" {
}
}
What would be the best practice for this? Any clarity on this would be appreciated.