Ok so I am trying to run this code but I keep on getting this error: fatal error: unexpectedly found nil while unwrapping an Optional value. I don't understand what it means or why im getting it. Can someone please help me. Thanks
query.whereKey("accepted", equalTo: PFUser.currentUser().username)
query.whereKey("username", containedIn: PFUser.currentUser()["accepted"] as [AnyObject])
All you have to do is this:
if let currentUser = PFUser.currentUser() {
query.whereKey("accepted", equalTo: currentUser.username)
if let someArrayObject = currentUser["accepted"] as? [AnyObject] {
query.whereKey("username", containedIn: someArrayObject)
}
} else {
// currentUser does not exist, do error handling
}
According to objective-c documentation of PFUser.currentUser(), which I'm assuming translates into a Swift optional, it could easily return nil. So you need to do something like:
if let currentUser = PFUser.currentUser() {
query.whereKey("accepted", equalTo: currentUser.username)
if let someArrayObject = currentUser["accepted"] as? [AnyObject] {
query.whereKey("username", containedIn: someArrayObject)
}
} else {
// currentUser does not exist, do error handling
}
Not sure what that second query line is, and what the someArrayObject is, so you might look further into that. But your error is either related to you dereferencing the currentUser() which could be nil, or the use of as and not as? in the second query line.
Solution to either is to use proper unwrapping of the potential optional values.
Related
I am parsing JSON data. After I start getting unexpectedly found nil while unwrapping an Optional value errors. I tried to use guard statement.
But again I am getting the same error.
guard let articleTitle = self.articles?[indexPath.row]["title"].string! else {return}
I simulate nil value like this:
guard let articleTitle = self.articles?[indexPath.row]["t"].string! else {return}
What I am doing wrong?
It doesn’t make much sense to force unwrap the optional in a conditional let assingment. Remove the !:
guard let articleTitle = self.articles?[indexPath.row]["title"].string else {return}
Otherwise the right-hand side will never produce nil but crash.
I am not able to figure this one out by my self. I am retrieving some settings stored in Core Data, and print these setting to some UITextFields. This works fine in another VC in the same project but here I get "unexpexpectedly found nil while unwrapping optional value".
I XCode I can see that the values are there? Why do I get this crash?
Please see attached screenshot.
This is the current code I am down to now. Still the same error message in XCode
func getSettingsFromCoreData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DeathMatchSettings")
do{
let results = try context.fetch(request)
let managedObject = results as! [NSManagedObject]
let getDMSettings = managedObject[0]
guard let playerOne = getDMSettings.value(forKey: "playerOne") else {
return
}
print(playerOne)
txtPlayerOne.text = String(describing: playerOne)
}catch{
fatalError("Error in retreiving settings from CoreData")
}
}
Player1 can be nil. You are trying to force downcast it to a value, but it is a fatal error in swift. Use an if let statement to test the value:
if let playerOne = getDMSSettings.value(forKey: "playerOne") as? String {
print(playerOne)
txtPlayerOne.text = playerOne
}
Read more about type casting in docs:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html
You can also use guard statement to unwrap your optional variable. It is better to use forced unwrapping only if you are confident that variable has non-optional value.
do {
guard let playerOne = getDMSettings.value(forKey:"playerOne") else {
return
}
print(playerOne)
txtPlayerOne.text = playerOne
}
I am new to Swift, FMDB and development in general and I and I am getting a fatal error at runtime : unexpectedly found nil while unwrapping an Optional Value. The error happens on the executeQuery line
Initial try and relevant code:
var rightAnswer:FMResultSet?
var memberDatabase:FMDatabase?
....
override func viewDidLoad() {
let path = NSBundle.mainBundle().pathForResource("1_celebs", ofType: "sqlite3")
memberDatabase = FMDatabase(path: path)
if memberDatabase!.open(){
print("database is ready")//it works if I comment out the stuff in loadquestion()
}
else{
print("error finding database")
}
...
func loadQuestion(){
let querySQL = "SELECT Quote, Answer, answerNumber, Celeb1, Celeb2, Celeb3, img1, img2, img3, feedbackImg, Context FROM celebs WHERE answeredRight = 'no' ORDER BY RANDOM() LIMIT 1"
rightAnswer = memberDatabase!.executeQuery(querySQL, withArgumentsInArray: queryParameters)
rightAnswer!.next()
So then I tried this in func loadQuestion()
let results:FMResultSet? = memberDatabase!.executeQuery(querySQL, withArgumentsInArray: nil)
while(results?.next() == true)
{...}
Then I tried this:
do{
rightAnswer = try memberDatabase!.executeQuery(querySQL, withArgumentsInArray: queryParameters)
while rightAnswer!.next(){...}
} catch let error as NSError {
print("failed: \(error.localizedDescription)")
}
Then, this:
do{
let rs = try memberDatabase!.executeQuery(querySQL, values: nil)
while rs.next(){...}
} catch let error as NSError {
print("failed: \(error.localizedDescription)")
}
and I get the same error on the executeQuery line every time! If I try to get away with getting rid of the exclamation and question marks then I get an error on the console saying that the database could not be opened.
The problem is that memberDatabase is nil.
You should make sure you are populating that variable.
Another suggestion, you should avoid the force unwrap operator. It does bypass the compiler check for nil (or possible nil) values.
Swift does offer better solutions like
Conditional Unwrapping
if let memberDatabase = memberDatabase {
try memberDatabase.executeQuery(querySQL, values: nil)
}
Guard
guard let memberDatabase = memberDatabase else { return }
try memberDatabase.executeQuery(querySQL, values: nil)
for object in users {
if let user = object as? PFUser {
if user.objectId! != PFUser.currentUser()?.objectId {
self.usernames.append(user.username!)
self.userids.append(user.objectId!)
var query = PFQuery(className: "followers")
query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
query.whereKey("following", equalTo: user.objectId!)
Why do I get the fatal error on the line which says:
query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
query.whereKey("following", equalTo: user.objectId!)
I do not understand. How can this be solved?
In your if condition you use PFUser.currentUser()?. If this expression is nil presumably the condition will be true.
Then, when you force unwrap PFUser.currentUser()! you logically get a crash.
The same applies to user.objectId!.
code:
var json:NSString;
json = NSString(format:"{\"und\":[{\"value\":\"2324\"}]")
var data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
var dataDic:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:nil) as! NSDictionary
I formed my own json and when i try yo parse it give error as "Unexpectedly found nil while unwrapping an Optional value".I assume that the cause of issue is passing empty json for pasing.I do not know how to solve this problem?.thanks in advance
let jsonString = "{\"und\":[{\"value\":\"2324\"}]}"
if let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
var error: NSError?
if let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [String:AnyObject] {
if let dictionaries = jsonDict["und"] as? [AnyObject] {
for dictionary in dictionaries {
if let value = dictionary["value"] as? String {
println(value)
}
}
}
}
}
As Martin R suggested The problem is in your json String. so just modify it like this:
"{\"und\":[{\"value\":\"2324\"}]}"
You forgot to add } at last.
Without } it can not be cast as NSDictionary thats why it become nil at run time.
You cant declare a variable uninitialized as you did. Replace
var json:NSString
to
var json:NSString!
The exclamation declaration will automatically unwrap the optional value where it is used (so you do not need to write json!) but you need to ensure that it is initialized somehow.