leaving textfields blank - crash - swift 4 - ios

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.

Related

calling function in viewDidLoad crash

Calling parseString crashes my application. myOptionalString is getting set from didSelectRowAtIndexPath in a tableview. The information is definitely get passed to this view controller.
The method also works if called from a button press. But in any life cycle method I try I get unexpectedly found nil while unwrapping an Optional.
override func viewDidLoad() {
super.viewDidLoad()
if let myUnwrappedString = myOptionalString{
print(myUnwrappedString) //<-- prints out string
confidence.text = parseString(myUnwrappedString) //<-- unexpectedly found nil while unwrapping an Optional crash
}
}
//this method works if called on a button press but crashes in viewDidLoad
func parseString(myString: String)->String{
return myString.substringFromIndex(myString.rangeOfString(" ")!.endIndex)
}
Your error come from your function parseString, let's see why. If you see carefully your function you're make a force-unwrapping of an optional value in your case the myString.rangeOfString(" ")!. This is not recommended at all.
If we pass the string "Confidence: 63%" to the function the function works properly and returns "63%", but it works because it have the " " string inside, if for some reason you pass some string that don't have it it will crash (e.g "Confidence:63%").
So one of the correct ways of implement this function can be using the guard statement using optional binding avoiding any force-unwrapping:
func parseString(myString: String) -> String? {
guard let range = myString.rangeOfString(" ") else { return nil }
return myString.substringFromIndex(range.endIndex)
}
In the above function you return nil in case of not exist the " " in the string and avoid the runtime error.
I hope this help you.
I'm guessing your problem lies in this line:
myString.rangeOfString(" ")!
rangeOfString returns an optional Range<Index>? value, meaning that if the character you are looking for is not present in the string, you will get the value nil in return. In other words, if there is no space in your string, you get a nil value for your range.
That value you then force unwrap with !, and then you use it to call substringFromIndex. This means that if the range was actually nil, you use that nil value to try to create a substring from its endIndex... which you cannot...so it crashes.
One way of solving this could be to use a guardto make sure that you actually found a range in your string. If you don't, then you just return an empty String...or do something else that suits your use case better.
Here is an example:
func parseString(myString: String)->String{
guard let range = myString.rangeOfString(" ") else {
return ""
}
return myString.substringFromIndex(range.endIndex)
}
Hope that helps you.

fatal error: unexpectedly found nil while unwrapping an Optional value formatter issue

Im creating simple app where i can manipulate my display which holds numbers(double). App works perfectly on simulator but not on a real device.
I found the reason for that error. Its my getter. Its returning nil(pretty sure about that) Anyone got idea how to fix my getter?
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = String(format: "%g", newValue)
}
}
You must be trying to get value of displayValue before assigning it any value, and your are force unwrapping it so, obviously it will crash.
In your current code just try setting value to your display label (like display.text = "5") before accessing it, then it would work.
And its better to use if let check in case of force unwrapping, if you know your variable value can be nil.
This solves everything. Thanks https://stackoverflow.com/users/2227743/eric-d
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html#//apple_ref/doc/uid/TP40014097-CH21-ID245

Tip Calculator - unexpectedly found nil while unwrapping an Optional value

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)

Swift Optionals - Unexpectedly found nil when unwrapping an optional value

I'm new to Swift and have been trying to wrap (ha) my head around optional values. As far as I can see - although I'm probably wrong - variables can be optional and therefore contain a nil value and these have to be accounted for in code.
Whenever I hit the 'save' button in my application I get the error: 'fatal error: unexpectedly found nil while unwrapping an Optional value'.
#IBAction func saveTapped(sender: AnyObject) {
//code to save fillup to Parse backend
// if variable is not nil
if let username = PFUser.currentUser()?.username {
// set username equal to current user
self.object.username = username
}else{
println("PFUser.currentUser()?.username contained a nil value.")
}
// if variable is not nil
if let amount = self.amountTextField.text {
//set amount equal to value in amountTextField
self.object.amount = self.amountTextField.text
}else{
println("self.amountTextField.text contained a nil value.")
}
// if variable is not nil
if let cost = self.costTextField.text {
// set cost equal to the value in costTextField
self.object.cost = self.costTextField.text
}else{
println("self.costTextField.text contained a nil value.")
}
// set date equal to the current date
self.object.date = self.date
//save the object
self.object.saveEventually { (success, error) -> Void in
if error == nil {
println("Object saved!")
}else{
println(error?.userInfo)
}
}
// unwind back to root view controller
self.navigationController?.popToRootViewControllerAnimated(true)
}
Not sure if the error is because of something in this block of code or somewhere else - can provide the main class code if needed.
Any help anyone can provided would be really appreciated as this has been bugging me for a while now.
From your code and the comments it sounds like your issue definitely lies with self.object
Your code never uses an if let statement to check to ensure self.object is not nil
Using println(username) works because your username is not nil. But when you try to call self.object.username, it's the self.object that is causing the crash.
You may have a property in your implementation like var object:CustomPFObject! which means, the first time you access this variable it's expected to not be nil. You'll probably want to check the code where you are setting self.object for the first time, and to make sure that it's being set before you've tried to access it.
If you're not able to manage when self.object is set, and when it's accessed, then change your declaration to var object:CustomPFObject? Now it's an optional, and as you write your code you'll be forced to make decisions as you go along.
For example:
var object:CustomPFObject?
let text = self.object.username //won't compile
let text = self.object!.username //mighty crash
let text = self.object?.username //you're safe, 'text' just ends up nil
I hope this helps you solve your issue.

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