fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) - ios

I get this Error:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
When I call this function:
ViewController().textToLabel(answer: answerLabel)
I call this from a different class:
func textToLabel(answer: String){
answerLabel.text = answer //I get the error here
}
Second View Controller
import Foundation
import UIKit
class germanClass{
func forGerman(){
var answerLabel = ""
var voiceText = ""
var colorPicker = "white"
var randomNumber = arc4random_uniform(UInt32(numberOfAnswers + 1))
switch (randomNumber){
case 0...20:
answerLabel = "Ja😋"
voiceText = "Ja"
colorPicker = "green"
}
//ViewController().changeColor(color: colorPicker)
ViewController().textToLabel(answer: answerLabel)
if (voiceTextOn){
randomNumber = arc4random_uniform(UInt32(7))
if (randomNumber == 0){
if (userName != "Ich möchte wissen wie du heißt! 😉" || userName != "du"){
voiceText += userName
}
}
}
textToSpeech().siriVoice(language: "de-de", text: voiceText)
}
}

Based on what you've shown, I'd say you are sending a label where you should be sending label.text
Either send the text or send the label and define your method accordingly.

Calling ViewController().textToLabel(answer: answerLabel) will instantiate a new ViewController and call textToLabel(answer:) on it, which is probably not what you want.
If you're trying to pass data between two view controllers you will have to find some other way to do it, depending on the relationship between them.
Also, your second view controller should inherit from UIViewController (as any view controllers should).

Related

Swift, EXC_BAD_Instruction

My program should fitch the data from an array, and put it in a tableView
var rideTime: String!
var rideLocation: String!
var RideDriver: String!
rideTime = RidestList[indexPath.row].TimeX!
rideLocation = RidestList[indexPath.row].LocationX!
RideDriver = RidestList[indexPath.row].DriverNameX!
cell.DriverX.text = rideTime;
cell.TimeX.text = rideLocation;
cell.LocationX.text = RideDriver;
return cell
In the cell.DriverX.text=rideTime it gives me EXC_BAD_Instraction
And a "atal error: unexpectedly found nil while unwrapping an Optional value
(lldb) " error appears, can anyone help?
if let ride_time = RidestList[indexPath.row].TimeX
{
cell.DriverX.text = ride_time
}
if let ride_location =RidestList[indexPath.row].LocationX
{
cell.TimeX.text = ride_location
}
if let river_driver =RidestList[indexPath.row].DriverNameX
{
cell.LocationX.text = river_driver
}
this could help you with your problem
The crash is basically due to no value coming to your variable rideTime. Best practice is use of optional binding var rideTime: String? to the variables which can expect null values. This will restrict the crash that you faced.

Multidimensional Array Unwrapping an Optional

so I'm having this problem where I can't unwrap an optional for outputting it into the label, I've even tried just printing it in the console and it still gives me an optional
The code and array are in different files.
Code It's in a VC:
for var i = 0; i < stateName.count; i++ {
if tax.state == stateName[i][0] {
stateName[i][1] = Double(taxNumb.text!)!
print(stateName[i][1])
output.text = String(stateName[i][1])
}
}
Array Code I made this in an empty swift file:
var tax : Taxes? = nil
var stateName = [
["AK - Alaska", tax?.alaska!],
["AL - Alabama", tax?.alabama!],
["AR - Arkansas", tax?.arkansas!],
["AZ - Arizona", tax?.arizona!],
["CA - California", tax?.california!]
]
As I wrote in my comment to your previous question use the "Nil Coalescing" ?? operator:
output.text = String(stateName[i][1] ?? "not set")
Or using the alternate swift String magic
output.text = "\(stateName[i][1] ?? "not set")"
The operator returns the first value if it not nil, otherwise it returns the second value.

How do I get the button to listen to the segmented control in Swift?

I am trying to build a temperature converter app. I used the segmented control for users to select how the temperature should be calculated (Celsius to Fahrenheit and from Fahrenheit to Celsius). I've also created a button that would convert the temperature entered by the selected method in the segmented control.
Here's the function I've created in the controller:
#IBAction func convertTemp(sender: AnyObject) {
let t = Double(tempTextfield.text!)
let type = converterType.selectedSegmentIndex
let tempM = tempModel(temp:t!)
if type == 0 {
finalTemp.text = String(tempM.celsius2Fahrenheit())
}
if type == 1 {
finalTemp.text = String(tempM.fahrenheit2Celsius())
}
}
And here's what I have in my model.
class tempModel {
var temp: Double
init (temp:Double){
self.temp = temp
}
func celsius2Fahrenheit()->Double{
return 32 + temp * 5 / 9;
}
func fahrenheit2Celsius()->Double{
return (temp - 32) * 5/9;
}
}
I'm not sure what I'm doing wrong. Everything but the Button(convert) works the way I want it to work. I can't seem to find the error.
And I don't know if this helps but I get this error:
2015-11-16 18:07:02.496 TemperatureConverer[5201:194432] Can't find keyplane that supports type 8 for keyboard iPhone-Portrait-DecimalPad; using 4131139949_Portrait_iPhone-Simple-Pad_Default
2015-11-16 18:07:04.827 TemperatureConverer[5201:194432] Can't find keyplane that supports type 8 for keyboard iPhone-Portrait-DecimalPad; using 4131139949_Portrait_iPhone-Simple-Pad_Default
(lldb)
I found a temporary fix. My problem was communication between my viewController and my tempModel. My code worked when I removed the tempModel class and inserting the method directly into the function in my controller.
So in my controller, I have this..
#IBAction func convertTemp(sender: AnyObject) {
let temp = Double(tempTextfield.text!)!
var newTemp = ""
if converterType.selectedSegmentIndex == 0{
newTemp = String(format: "%.2f Farenheit", 32+temp*5/9)
}
if converterType.selectedSegmentIndex == 1{
newTemp = String(format: "%.2f Celsius",(temp-32)*5/9)
}
finalTemp.text = newTemp
}
I know eventually I would have to learn how to link my controller and model together . But until I figure it out, this is one solution that fixed my problem.

Swift: Checking for the existence of a uitextfield

I have a controller that will have a variable number of textfields. On a button press I want to check for the existence of, whether or not its empty, and check the character count of the input.
I'm trying the following, which works fine if homePhone exists
if homePhone?.text != ""{
if countElements(homePhone1.text) != 10{
validInput = false
validationError = "Home Phone must be 10 digits"
}
}
But when a textfield does not exist (mobile) I get a fatal error
if mobilePhone?.text != ""{
if countElements(mobilePhone.text) != 10{
validInput = false
validationError = "Mobile Phone must be 10 digits"
}
}
fatal error: unexpectedly found nil while unwrapping an Optional value
Obviously I'm not doing the check correctly, optionals and unwrapping is continually tripping me up.
You can unwrap your textfield and check if it exists:
if let mobilePhoneField = mobilePhone{
if mobilePhoneField.text != ""{
if countElements(mobilePhoneField.text) != 10{
validInput = false
validationError = "Mobile Phone must be 10 digits"
}
}
}
This will check if your optional variable is nil or not so you can safely unwrap it, actualy it will do it for you.
if let value = myOptionalVariable{
//my optionalVariable is not nill i can do whatever i want
value.text = "Yaay"
}

Error in adding an element to [String:Array<NSDictionary>] in Swift

I have a property in my model of Type : [String:Array<NSDictionary>].
I want to add elements to this, in a loop. So this is what I do :
for var k=0;k<body.count;k++ {
var dict=body[k] as NSDictionary
if(k==0) {
self.model.data[i]!=[dict]
}
else {
self.model.data[i]!.append(dict)
}
}
When I do this, I get the following error :
fatal error: unexpectedly found nil while unwrapping an Optional value
The constructor initializes model.data to data=[String:Array<NSDictionary>]().
Please Help. Thanks in advance.
The problem is probably that you are unwrapping self.model.data[i] when you assign [dict] to it. I assume you are doing that in the case where data[i] has no value yet. So the forced unwrap will result in a nil pointer, which causes a crash.
Try this:
for var k=0;k<body.count;k++ {
var dict=body[k] as NSDictionary
if(k==0) {
self.model.data[i]=[dict]
}
else {
self.model.data[i]!.append(dict)
}
}
Although this assumes that self.model.data[i] exists for the case where k is not equal to 0. I am not sure if that is correct, you don't provide enough details.
What I think you are trying to do is this:
for var k = 0; k < body.count; k++ {
var dict = body[k] as NSDictionary
if self.model.data[i] == nil {
self.model.data[i] = []
}
self.model.data[i]!.append(dict)
}

Resources