Tip Calculator - unexpectedly found nil while unwrapping an Optional value - ios

I am having a problem with my app. I am trying to get 15% of what is entered in a textbox to show up in a label after a push of a button. Here is my code so far:
#IBAction func calculateButton(sender: UIButton)
{
var fifteenPercent: Double
fifteenPercent = 0.15
var billTop = billTextField.text.toInt()!
var billTipped: Double
billTipped = Double(billTop) * fifteenPercent
tipAmountLabel.text = "$\(billTipped)"
When I start the app and push the button, I get the error
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

It looks like your issue is unwrapping the string to an int, try getting it this way:
var billTop = (billTextField.text as NSString).doubleValue

Smells like your billTextField doesn't have it's IBOutlet hooked up. You're forcing the unwrap of the text in billTextField. If that's nil it will blow up.

Add like this:
var billTop = Int(txt_address.text!)
tipAmountLabel.text = String(format:"$%.2f", billTipped)

Related

leaving textfields blank - crash - swift 4

I am trying to create a course avg calculator with textfields. However if I only want to enter in a few marks (i.e. not filling out all the textfields) I get a crash.
I get this error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
In my code, I tried to avoid this nil value, but I get the error on that first line if I leave the first textfield blank. I do further calculations with these textfields, so I'm not sure if I will get similar errors once I fix these lines.
if b?.text != nil {
b?.text = String(Double(b!.text!)!/100)
}
if d?.text != nil {
d?.text = String(Double(d!.text!)!/100)
}
if f?.text != nil {
f?.text = String(Double(f!.text!)!/100)
}
if h?.text != nil {
h?.text = String(Double(h!.text!)!/100)
}
Force unwrap the double conversion
Double(b!.text!)!
is the reason as empty string can't be converted to double so it returns nil and as you use ! , hence the crash , you need
if let tex = b , content = tex.text , value = Double(content) {
print(value)
}
Also don't make the b var an optional make it !
var b:UITextField! // and make sure you init it
Edit: Don't create other vars to hold instance ones use them directly
#IBOutlet weak var weight1: UITextField!
if let content = weight1.text , value = Double(content) {
print(value)
weight1.text = "\(value/100)"
}
Double(b!.text!)!
This is the reason, your input text (b!.text!) is not convertible to double hence ended up with nil.
for ex: you might be giving input "12Th45", this is not convertible to double.
Always use optional binding wherever you are not sure that value is there or not.
Thanks.

Pass data between 2 ViewControllers [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 5 years ago.
I'm trying to send data from my first ViewController to my second One.
It works fine with a simple Int but with this Double it doesn't work and I don't understand why. So if you can explain why it doesn't work it's cool !
My declaration in first ViewController :
var time: Double? = 0.00
Then I try to send it to my other ViewController:
let vc = segue.destination as! MySecondViewController
vc.rows = rows[pathForAVC]
vc.lap = lap[pathForAVC]
vc.indexPath = pathForAVC
vc.time = rows[pathForAVC]["Time"]! as! Double
fatal error: unexpectedly found nil while unwrapping an Optional value
And my second ViewController:
var time: Double? = 0.00
topLabel.text = "\(time!)"
N.B:
rows is a Dictionnary:
var rows: [[String : AnyObject]] = [[:]]
I really don't understand my mistake...
The problem is that you are force unwrapping a value that may not be there:
vc.time = rows[pathForAVC]["Time"]! as! Double
If rows[pathForAVC]["Time"]! is nil, your application will crash. You should really avoid using ! unless your application simply cannot continue operating without that value. And those situations should be rare.
You should instead safely unwrap your value using an if let statement like this:
if let unwrappedTime = rows[pathForAVC]["Time"] as? Double {
print(unwrappedTime)
}
(I'm not near Xcode right now but the above code should be close enough to get valuable hints from the compiler).
Let me know if you need any more clarification.

SWIFT coding error: fatal error: unexpectedly found nil while unwrapping an Optional value

var filteredImage: UIImage?
var originalImage = UIImage(named: "scenery")
var imageProcessor: ImageProcessor!
var activeFilter: ImageProcessor.Filter!
#IBAction func applyFilter(sender: UIButton) {
activeFilter = ImageProcessor.Filter(rawValue(sender.titleLabel?.text)!)
print(activeFilter)
filteredImage = imageProcessor.process(originalImage!, filter: activeFilter!, parameter: 0.5)
}
Here`s a part of the code, when I run it, it shows
fatal error: unexpectedly found nil while unwrapping an Optional value
on "filteredImage = imageProcessor.process(originalImage!, filter: activeFilter!, parameter: 0.5)"
I thought some parameters must be nil so I check throughly but I failed.
Are you sure "scenery" exists in your image.assets?
I`ve already solve this question
the key is I forgot to define imageProcessor
so by adding "var imageProcessor: ImageProcessor!"
It`s done
thanks for you guys help anyway!

unexpectedly found nil while unwrapping an Optional value uint32 swift

When I try to set my results label to this string containing a UInt32 my app crashes and I get the error message "unexpectedly found nil while unwrapping an Optional value".
I figured that meant I just have to add a ! to the variable but when I try that I get the issue "Operand should have optional type, has type UInt32.
var fingers = arc4random_uniform(6)
result.text = "Incorrect, I am holding up \(fingers) fingers"
This will surely work:
var result: UILabel = UILabel()
var fingers: UInt32 = arc4random_uniform(6)
result.text = "Incorrect, I am holding up \(fingers) fingers"
println("\(result.text)")

fatal error: unexpectedly found nil while unwrapping an Optional value(When adding to a array)

I have some code that receives value from a segue and replaces a certain element of an array with the index number that I have.
The initialization of the variables is:
var noteTitles: [String] = ["Sample Note"]
var noteBodies: [String] = ["This is what lies within"]
var selectedNoteIndex: Int!
var newTitle: String!
var newBody: String!
and I have a segue that makes the last 3 values the values that I want them to be.
under viewDidLoad(), I have this:
if newTitle == nil && newBody == nil {
}
else {
println("\(newTitle)")
println("\(newBody)")
println("\(selectedNoteIndex)")
let realTitle: String = newTitle
let realBody: String = newBody
let realIndex: Int = selectedNoteIndex
noteTitles[realIndex] = realTitle
noteBodies[realIndex] = realBody
}
My logs show this:
New Note Title
This is what lies within
nil
fatal error: unexpectedly found nil while unwrapping an Optional value
and I get
Thread 1: EXC_BAD_INSTRUCTION(code=EXC_i385_INVOP,subcode=0x0)
on the line
let realIndex: Int = selectedNoteIndex
Can anyone tell me what I'm doing wrong?
var varName: Type! declares an implicitly unwrapped optional.
It means that it will be automatically unwrapped when accessing the value with varName, i.e. without using varName!.
Thus, accessing the implicitly unwrapped optional selectedNoteIndex with let realIndex: Int = selectedNoteIndex when its value is actually nil results in the error you got.
Apple's Swift Guide states that:
Implicitly unwrapped optionals should not be used when there is a
possibility of a variable becoming nil at a later point. Always use a
normal optional type if you need to check for a nil value during the
lifetime of a variable.
The reason I was getting these errors is because while segueing back to the main view, I was not using the proper unwind segue, and instead using another show segue, which erased all data that had previously been within the view controller. By creating a unwind segue, I was able to keep the values before the segue to the detail view and prevent the error.
Because you did not assign value for selectedNoteIndex so it shows nil. First, you have to check whether its not nil value.
if let selectedNoteIndex = realIndex{
let realIndex: Int = selectedNoteIndex
}

Resources