unexpectedly found nil while unwrapping an Optional value uint32 swift - ios

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)")

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.

Swift convert Any to String and assign to UIlabel (Fatal error: Unexpectedly found nil while unwrapping an Optional value) [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 have this Dictionary
var detailItem: Dictionary?
I am trying to get the Any and convert it to a String and then assign to UILabel like so:
self.firstName.text = detail!["firstname"] as? String
Fatal error: Unexpectedly found nil while unwrapping an Optional value
Which I dont understand because first name is not nil, its James (not "James") but just James, if I print it I can see it:
print(detail!["firstname"])
What am I doing wrong?
How to do I assign Any to UiLabel text?
The safest way to do this is to unwrap the optional string value from your dictionary.
if let firstName = detail?["firstname"] as? String {
self.firstName?.text = firstName
}
This ensures your label's text will only get set when there is a value for "firstname" in your Dictionary.
If that still crashes then your label might be nil. If your using an outlet it might not be set.

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)

fatal error: unexpectedly found nil while unwrapping an Optional value [Tilting Issue]

For some odd reason, this line:
var x = motionManager.accelerometerData.acceleration.x
keep throwing an error like this:
fatal error: unexpectedly found nil while unwrapping an Optional value
this is the rest of the code around it:
var motionManager = CMMotionManager()
if motionManager.accelerometerAvailable == true {
motionManager.startAccelerometerUpdates()
var x = motionManager.accelerometerData.acceleration.x
NSLog("X: %i",x)
}
It takes some small amount of time before the hardware reports any accelerometer data, so I believe that's why you get that error. You might want to use startAccelerometerUpdatesToQueue:withHandler instead, and deal with the received data inside the handler.
var x = motionManager.accelerometerData.acceleration.x is throwing an error because motionManager.accelerometerData is an optional and it can be nil. Check for the value and unwrap it if it exists, otherwise do not try and unwrap the optional when its nil.

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