Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Ben Barry
491 PointsCheck to see if NSDate is empty
Using Swift I want to check to see if a date is present before doing formatting to it, but the following code does not work. Any Ideas?
if(date != nil){ //do your formatting here }
Steve Hunter
57,712 PointsOK - so how is the user prompted to enter the date - is that some front-end GUI? It may be better to add validation there in the form of a regular expression, or such like, rather than writing incorrect data to the back end and testing for that when you pull the wrong data out again. It strikes me that the point of entry is the bit that needs parsing for correctness.
Regular expressions are great but they are not written to be easily understood! There's a couple of sites:
http://www.regular-expressions.info/dates.html http://www.labnol.org/internet/regular-expressions-forms/28380/
Steve.
1 Answer
Steve Hunter
57,712 PointsYou can test that the description isn't empty, perhaps?
let date = NSDate()
date.description != "" // this evaluates to true - for your if statement
I think a valid date will have a description which is a text representation of the date. So it'll never be an empty string.
I hope that makes sense!
Steve.
Ben Barry
491 PointsThat still does not work, but I probably did not give you enough information to answer it. So basically I have a NSDate that gets saved as Core Data attribute. When fetching the saved date, I want to make sure that the date is actually there before formatting it as a string to show up on the UI.
but doing the if(date.description != "") Still evaluates to true even if it does not exist in the core data fetch.
Thanks,
Ben
Steve Hunter
57,712 PointsOK - so what are the options? Is it either an NSDate or nil or can it be something else?
Is testing it at the point of writing to the Core a better option? Can you validate the entry in the store?
Sorry, but this isn't my area at all! I'm probably talking nonsense.
Steve.
Ben Barry
491 PointsBen Barry
491 PointsThanks for the quick reply. I think it can only be a NSDate or nil, but since I am very new to core data and iOS programming I may be wrong.
The idea is that if someone has not entered the date to give them an opportunity to do so.
This is not my area either. So I appreciate your help.
Ben