user11182249
user11182249

Reputation:

Unexpectedly found nil while implicitly unwrapping an Optional value despite conditional binding

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?

Upvotes: 1

Views: 12427

Answers (2)

RomuloVitoi
RomuloVitoi

Reputation: 117

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"

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100541

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

Upvotes: 2

Related Questions