Swift, print issue when use ? and ! variables [duplicate] - swift

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I got access error('fatal error: unexpectedly found nil while unwrapping an Optional value') when print variable p02. According to the error message, I still cannot understand the reason.
var p02:Person! = nil
var p03:Person? = nil
if (p02==nil)
{
print("p02 is nil")
}
if (p03==nil)
{
print("p03 is nil")
}
print(p03)
print(p02)
Anyone know why,
Thanks

cause it always tries to print p02 and p03 even if they are nil
try this
var p02:Person! = nil
var p03:Person? = nil
if (p02==nil)
{
print("p02 is nil")
}else{
print(p02)
}
if (p03==nil)
{
print("p03 is nil")
}else{
print(p03)
}

Related

Found Nil When Unwrapping Optional Value, I keep getting this [duplicate]

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.
im having this problem: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
is there any way to solve it?
this is my code:
let ref = Database.database().reference()
ref.child("ChildA").child("Title").observeSingleEvent(of: .value, with: { DataSnapshot in
print(DataSnapshot) // replace this with textLabel or other item
let m = DataSnapshot.value as? String
self.TitleA.text = m //Error in this line
})
Replace:
self.TitleA.text = m
With this:
self.TitleA?.text = m ?? ""

please give me some solution to this error Thread 1: 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 3 years ago.
func doGetLocalDataUser() -> logInResponse {
var localData : logInResponse? = nil
if let userData = UserDefaults.standard
.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA),let user = try? JSONDecoder()
.decode(logInResponse.self ,from: userData){
localData = user
}
return localData!
}
I would change the method to this:
func doGetLocalDataUser() -> logInResponse? {
guard let userData = UserDefaults.standard.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA), let user = try? JSONDecoder().decode(logInResponse.self ,from: userData) else {
return nil
}
return user
}
Keep in mind JSON decoding can fail (maybe has wrong format), therefore user will be nil, and this method can return nil
localData is nil, so you are force unwrapping localData (as a logInResponse) illegally.
If your optional chaining finds nil at any point (for example your userData doesn't exist in UserDefaults / has the wrong type) then it won't execute.
You are declaring this doGetLocalDataUser() function to return a non optional logInResponse type and force unwrapping a nil value to try and retrieve one. Best practice is to avoid the force unwrap "bang" operator "!" because it can lead to fatal errors like this.
Simple solution is to change your method to return an optional logInResponse? type, and eliminate the bang operator:
func doGetLocalDataUser() -> logInResponse? {
if let userData = UserDefaults.standard.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA), let user = try? JSONDecoder().decode(logInResponse.self ,from: userData){
return user
} else {
return nil
}
}

Fatal error: swift 2.3 when unwrapping value [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I'm trying to send a saved string to the apple watch with WCsession methode. But when I do this I get an error in swift 2.3: fatal error: unexpectedly found nil while unwrapping an optional value !!
func Reloadip() {
let ip = nsdefauts.object(forKey: saved)
let requestValues = ["send" : "A" , "IP" : ip as! String ]
print(requestValues)
if(WCSession.isSupported()){
session!.sendMessage(requestValues, replyHandler: nil, errorHandler: nil)
print("sended ip")
}
}
the error is made at the "ip as! String line" how can I fix this. ?
regards Quinn
You should use more safe code instead
func Reloadip() {
guard let ip = nsdefauts.objectForKey(saved) as? String else {
print("there is no saved ip")
return
}
let requestValues = ["send" : "A" , "IP" : ip]
print(requestValues)
if(WCSession.isSupported()){
session?.sendMessage(requestValues, replyHandler: nil, errorHandler: nil)
print("sended ip")
}
}

unexpectedly found nil while unwrapping an Optional value while reading from DS with fromCString

I am reading from a dbtable and get an error at a specific position of the table. My sql is ok, because I could already read from the same table, but at a specific row I get an error and I would like to know howto handle this error. I am not looking for a solution to solve my db-issue, I am just looking for handling the error, so it doesn't crash.
I have the following code :
let unsafepointer=UnsafePointer<CChar>(sqlite3_column_text(statement, 2));
if unsafepointer != nil {
sText=String.fromCString(unsafepointer)! // <<<<<< ERROR
} else {
sText="unsafe text pointer is nil !";
}
I get an error:
"fatal error: unexpectedly found nil while unwrapping an Optional value"
at line marked with <<<<<< ERROR.
The unsafe pointer's value is not nil:
pointerValue : 2068355072
How can I handle this error, so my app is not crashing ?
Another possible solution is this:
let unsafepointer=UnsafePointer<CChar>(sqlite3_column_text(statement, 2));
var sText = "unsafe text pointer is nil !";
if unsafepointer != nil{
if let text = String.fromCString(unsafepointer) as String?{
sText = text;
}
}
let statementValue = sqlite3_column_text(statement, 2)
var sText = withUnsafeMutablePointer(&statementValue) {UnsafeMutablePointer<Void>($0)}
if sqlite3_column_text(statement, 2) != nil {
print("do something")
} else {
YourString = ""
}

swift fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 1 year ago.
I am programming a small social network app for a community in Swift.
I got the error: fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) when I try to change views with self.presentViewController(FeedViewController(), animated: true, completion: nil). This line of code only executes if the user is allowed access to the second page.
Here is the full code:
#IBAction func loginButtonPressed(sender: AnyObject) {
if passwordTextField.text == "" || nameTextField.text == "" {
Global.showAlert("Erreur", message:"Nom d'utilisateur ou mot de passe invalide!", view:self)
} else {
PFUser.logInWithUsernameInBackground(nameTextField.text, password:passwordTextField.text) {
(user: PFUser!, error: NSError!) -> Void in
if user != nil {
} else {
// The login failed. Check error to see why.
//var err = error.userInfo["error"] as NSString
Global.showAlert("Erreur", message:"Nom d'utilisateur ou mot de passe invalide!", view:self)
}
}
Based off be comments above it sounds like your app is crashing after the login. If that's the case:
Try changing user!=nil to error == nil
UPDATE
Check class permissions