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"
Related
I have declared a type called "JournalEntry" as an optional and have it set to nil. Then when the VC loads I test to make sure that the object has been injected before trying to use it, but I get an error that says "Comparing non-optional value of type 'JournalEntry' to nil always returns true".
But I have it set as an optional and to nil...
Here's the code:
class AddJournalEntryVC: UIViewController, UITextViewDelegate {
var willEdit:Bool?
var entryForEdit:JournalEntry? = nil
override func viewDidLoad() {
super.viewDidLoad()
if isEditing {
guard let entry = entryForEdit, entry != nil else{ //Comparing non-optional value of type 'JournalEntry' to nil always returns true
return
}
dateLabel.text = entry.dateString!
timeLabel.text = entry.timeString!
timestamp = entry.timestamp!
}
}
Where has my thinking gone wrong? Thank you.
Just remove the entry != nil clause and it will work as you require. The if let statement that proceeds it performs the not-nil check already.
guard let entry = entryForEdit else {
return
}
In my UITableViewController, I have an optional property which is a CNContact. If not nil, I want to populate some text fields with the contact's data.
Here is the property:
var contact: CNContact? = nil {
didSet {
if contact != nil {
prefillFromContact(contact!)
}
}
}
And here is the code setting a text field
func prefillFromContact(con: CNContact) {
print(con.givenName)
firstNameTextField.text = con.givenName
}
The print statement works, and returns the contact's name, but the following line throws an error.
Kate
fatal error: unexpectedly found nil while unwrapping an Optional value
I can't work out why it works on the print statement, but not the following line.
I assume firstNameTextField is declared as an implicit optional, like this:
var firstNameTextField: UITextField!
And you are causing this code to be called before viewDidLoad.
If so, firstNameTextField is nil. It is only possible to set the values of UIViews loaded from XIB/Storyboards once they are loaded. Before that, their outlets are nil.
As an aside (even though this isn't what is causing your problem):
if contact != nil {
prefillFromContact(contact!)
}
is more Swifty like this:
if let contact = contact {
// this is only true if contact != nil, and you have a contact variable
// that is of type CNContact, not CNContact?
prefillFromContact(contact)
}
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 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!)"
}
I'm using CLGeocoder for reverse geolocation and get array of CLPlacemark. When I use GPS outside the US (i.e. -27,127) and then access placemark.postalCode, the app crashes with:
"fatal error: unexpectedly found nil while unwrapping an Optional value".
It seems, that placemark.postalCode is nil where no postal code is available. But postalCode return type in Swift is String!:
var postalCode: String! { get } // zip code, eg. 95014
So I can't even test is for nil, because the crash is caused by the getter of postalCode.
Any ideas how to prevent this crash? Thank you!
Being an optional, even if implicitly unwrapped, you can check it for nil:
if placemark.postalCode != nil {
}
and the app won't crash because of that :)
To prove it, just try this code in a playground, where 2 implicitly unwrapped properties (a computed and a stored) are checked for nil:
struct Test {
var nilComputed: String! { return nil }
var nilStored: String! = nil
}
var test = Test()
if test.nilComputed != nil {
print("It's not nil")
} else {
print("It's nil")
}
if test.nilStored != nil {
print("It's not nil")
} else {
print("It's nil")
}