Reputation: 157
I define a class in Swift like the following:
var moduleName : String?
var moduleWeight : Float = 0
var moduleMark : Double = 0.0
var moduleCompletion : Int = 0
var moduleNotes : String?
I have another function that accesses these variables
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//
if segue.identifier == "courseWorkTopView"
{
if let topViewController = segue.destination as? assignmentTopViewController{
topViewController.moduleName = detailItem?.moduleName
topViewController.moduleWeight = detailItem?.value
}
}
}
I get the error:
Value of optional type 'Float?' not unwrapped; did you mean to use '!' or '?'?
I tried the following code as well
topViewController.moduleWeight = (detailItem?.value)!
But I get a run time error:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I'm new to swift and it will be great if someone could help to fix this issue
Upvotes: 0
Views: 741
Reputation: 17864
detailItem
is nil. If you want to avoid the crash, you can use
topViewController.moduleWeight = detailItem?.value ?? 0
(or use any other reasonable default), or do
if let topViewController = segue.destination as? assignmentTopViewController, let detail = detailItem {
topViewController.moduleName = detail.moduleName
topViewController.moduleWeight = detail.value
}
Upvotes: 1
Reputation: 6067
you can solve like that
topViewController.moduleWeight = detailItem?.value ?? 0
or change moduleWeight as optional
var moduleWeight : Float?
and use it normal
topViewController.moduleWeight = detailItem?.value
Upvotes: 1