I have textfield and i need to put inside session value and when i add gives me
fatal error: unexpectedly found nil while unwrapping an Optional value
error
My codes here
#IBOutlet weak var discountField:UITextField!
func textFieldDidEndEditing(textField: MPGTextField_Swift, withSelection data: Dictionary<String,AnyObject>){
let displayDiscount : AnyObject? = data["discount"]
let addClientDiscount:String = (displayDiscount as? String)!
prefs.setObject(addClientDiscount, forKey: "addClientDiscount")
self.discountField.text = "\(addClientDiscount)" // THIS LINE GIVES ERROR
}
Also PROPERTLY Have ! in referencing Outlets
Thanks
Handle your line of error as follows:
self.discountField.text = data!["discount"] as? String ?? ""
If data["discount"] has a value, it will be assigned to the textfield, else an empty string will be used. But it will avoid the crash due to a nil value.
As suggested by many other guys, first check your IBOutlet connection.
If it's properly set, then put '?' after addClientDiscount as:
self.discountField.text = "\(addClientDiscount?)"
Because if this line
let displayDiscount : AnyObject? = data["discount"]
gives nil then crash may occur.
So to bypass that crash put '?'
UPDATE
As suggested by Eric D.
we can also do this:
if let displayDiscount = data["discount"] {
let addClientDiscount = displayDiscount as! String
prefs.setObject(addClientDiscount!, forKey: "addClientDiscount")
self.discountField.text = "\(addClientDiscount!)"
}
Related
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 2 years ago.
#IBOutlet var folderPathAC: NSArrayController!
static var appDelegate = NSApplication.shared.delegate as! AppDelegate
static var context = appDelegate.persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
updateUITable()
// Do any additional setup after loading the view.
}
func updateUITable(){
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "FolderPaths")
//request.predicate = NSPredicate(format: "age = %#", "12")
request.returnsObjectsAsFaults = false
do {
let result = try ViewController.context.fetch(request)
for data in result as! [NSManagedObject] {
let name = data.value(forKey: "folderName") as! String
let path = data.value(forKey: "folderPath") as! String
let folder = FolderPath(path: path, name: name)
self.folderPathAC.addObject(folder)
}
} catch {
print("Failed")
}
}
I am using the above code to populate a table view at the time of the app start in a macOS app. However, I am getting the following exception in the AppDelegate class at the runtime.
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I am new to Mac development.
The most common cause of these are:
failure to unwrap an optional — This can be a forced unwrap (!) or an implicit unwrap (accessing an implicitly unwrapped optional that’s nil).
a failed forced cast (as!), either because the value was a nil optional or because the value was of the wrong type.
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 3 years ago.
I need to take the response of the alamofire closure and send it to another class. I get the response inside the closure but when I try to send to the other class, I get: "Fatal error: Unexpectedly found nil while unwrapping an Optional value"
I need to get the response from the closure and set it in a IBOutlet from another class.
Also I try to set the closure response in a variable global and I get the same error.
class DrawInformationViewController: UIViewController {
#IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
class RequestViewController: UIViewController{
var getName: String?
func testAlamofire(){
if let JSON = response.result.value{
self.jsonArray = JSON as? NSArray
//this for doesn't matter it is just for an example, to get the idea
for item in self.jsonArray! as! [NSDictionary]{
let name = item["name"] as? String
print(name) //until here everything is ok
//the problem is when I try to send this value
DrawInformationViewController().nameLabel.text = name //here is when it get the error: "Fatal error: Unexpectedly found nil while unwrapping an Optional value"
//Also I try to set the value in a global var
getName = name //There is not problem
}
}
}
}
func setValueFromClosure(){
DrawInformationViewController().nameLabel.text = getName
//Here I get the same error: "Fatal error: Unexpectedly found nil while unwrapping an Optional value"
}
}
Try initializing getName as follows:
var getName: String = ""
Cheers.
So I have the following lines:
let theUsername = "\(String(describing: selectedPost?.user.username!))"
if selectedPost?.user.username! != nil {
print("Contains a value!")
username.text = theUsername//Fails here
} else {
print("Doesn’t contain a value.")
username.text = "No username found: Weird"
}
The error message:
Unexpectedly found nil while implicitly unwrapping an Optional value
would make one think the value inside is nil. However when printing:
print("\(String(describing: selectedPost?.user.username!))", " LIT555")
I get:
Optional("C22AE009-8CC6-490A-9328-23A08AAD3A10") LIT555
How can I turn the value into a non optional (ie. get rid of the Optional() part), so it can work without it failing?
Try
if let res = selectedPost?.user.username { // to unwrap the optional value
// check textfield is not nil
username.text = res
}
else {
username.text = "default"
}
Or shortly
username.text = selectedPost?.user.username ?? "default"
According to the crash your textfield is nil , check the IB connection
When you do this
var selectedPost : Post? { didSet { getMediaStats() loadP3Data() } }
and assign a value to selectedPost in the prepare method of the previous vc , the destination vc outlets are still nil because it's not loaded yet and since didSet is called instantly before the load , hence the crash
So remove didSet and call what inside it in viewDidLoad
Even thought you're using ! at the username, this expression is still optional because you have the ? in selectedPost. I strongly suggest you to never use forced unwraps (!), always use if let or guard let to make sure you can unwrap an optional and avoid those crashes.
This is what your code could look like:
if let theUsername = selectedPost?.user.username {
username.text = theUsername
} else {
username.text = "No username found: Weird"
}
or
username.text = selectedPost?.user.username ?? "No username found: Weird"
While I try to pass it to temporary variables it doesn't seem to happen.
Although there are no errors while building the app, once I try to enter a value for "rateOfPaddy", it fails, citing "fatal error: unexpectedly found nil while unwrapping an Optional value"
Please let me know if I'm doing anything wrong, either related to Swift or Eureka?
form +++ Section()
<<< DateTimeRow() {
$0.tag = "RecordDateTag"
$0.title = "Date"
$0.value = NSDate()
}.cellSetup { cell, row in
cell.textLabel?.textColor = UIColor.blackColor()
}.onCellHighlight { _ in
if let dateInput = formInput["RecordDateTag"] as? String {
self.dateInputValue = dateInput
}
}.onCellUnHighlight { _ in
if let dateInput = formInput["RecordDateTag"] as? String {
self.dateInputValue = dateInput
}
}
I used .onChange callback to check and pass the information to local variables, which was of no use. .onCellHighlight and .onCellUnHighlight combination didn't do the trick either!!
Try calling values function as documented here
You can create a method like below and call it from onChange callbacks
func updateValues() {
let allFormData = formInput.values()
if let dateInput = allFormData["RecordDateTag"] as? String {
self.dateInputValue = dateInput
}
}
The error "fatal error: unexpectedly found nil while unwrapping an Optional value" means that you are trying to unwrap an optional that has nil as a value.
Verify that every formInput[KEY] has a value of the type you expect before forcing the unwrap with the as!
You could benefit from the Optional Binding
if let value = formInput["Some"] as? Int
{
//Value exist and is an Int
}
else
{
print("Not an Int")
}
For More references:
Swift Type Casting
Swift Optionals
I'm facing with an error: "unexpectedly found nil while unwrapping an Optional value"
when I insert new data in coreData and reload my tableview, I recall this function
var unique = [String]()
var loadMovie = [String:[Movie]]()
func insertMovie(movie : Movie) {
let genre = movie.genre!
if unique.contains(genre) {
loadMovie[genre]!.append(movie)
} else {
unique.append(genre)
loadMovie[genre] = [movie]
}
}
and fetch data:
func fetchAndSetResults() {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Movie")
do {
let movies = try context.executeFetchRequest(fetchRequest) as! [Movie]
loadMovie.removeAll()
for movie in movies {
insertMovie(movie)
}
} catch let err as NSError {
print(err.debugDescription)
}
}
and the app crushes for the error mentioned above on line: " loadMovie[genre]!.append(movie)" but if I reload app, my data are stored and visible in tableview. What's the problem?
you unwrapped optional variable means you just resolving the compile time error only. In swift you unwrapping the variable means it is represents that variable won't get the nil.You are just telling to the compiler .But now you are getting the nil (Run time Error) you need to handle this by using Optional Binding.
if let movies = try context.executeFetchRequest(fetchRequest)
{
loadMovie.removeAll()
}
Your variable loadMovie is a Dictionary with Strings as the keys and Arrays of Movies as what is stored for each key. If you are getting the error "unexpectedly found nil while unwrapping an Optional value" for line " loadMovie[genre]!.append(movie)" it means without a doubt the String called genre is sometimes not a stored as a key in your loadMovie Dictionary.
Use the code below to first make sure you can get the Array stored for that key (stored in the genre string), and if you can't then print out the String so you can debug, to find out what key is missing.
var unique = [String]()
var loadMovie = [String:[Movie]]()
func insertMovie(movie : Movie) {
let genre = movie.genre!
if unique.contains(genre) {
if let genreArray = loadMovie[genre]{
genreArray.append(movie)
} else {
NSLog("The missing genre: \(genre)")
}
} else {
unique.append(genre)
loadMovie[genre] = [movie]
}
}
Anytime you want a value that could be nil (not there) you can use the if/let pattern above. So for your second question in the comments you could replace return loadMovie[genre].count with:
if let genreArray = loadMovie[genre]{
return genreArray.count
} else {
return 0 // zero because there are no items
}
There are other ways too. You should checkout a good basic swift tutorial like: http://www.tutorialspoint.com/swift/
If you look at the section on optionals this should all be more clear. Here at stack overflow you are generally expected to first have tried to find out answers for yourself, and understand the basic theory. Unfortunately, that is why you are getting so many down votes. I hope this has helped.
If this has helped you please accept this answer by clicking on the checkmark next to it.