I am very new to swift and found this one difficult, so its saying that it cannot be parsed to a variable because its not a string.
I searched and found something but it was not related near to my type of code so I am kindly asking for it 🙂
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: NSDate? = dateFormatterGet.date(from: currentVechicle.LastCommunicationDate!) as NSDate?
print(dateFormatterPrint.string(from: date! as Date))
cell.perditsuarOutlet.text = date // Error: Cannot assign value of type 'NSDate?' to type 'String?'
2
Answers
your date constant is an NSDate.
and the cells text property is a String.
You can’t pair the two together since they aren’t the same type.
Since you can’t change the cells text type, that only leaves you with 1 option. You’ll have to turn the NSDate into a String.
I recommend taking a look at Paul Hudsons 100 Days of Swift. It was a fantastic resource when I first started. The link I’ve provided points to his lessons from Day 1 about Strings
Keep up the good work. I promise it gets better 🙂
You are printing the correct
String
value, but assigning the variabledate
which typed asNSDate?
to thetext
property, which should be aString
.Try doing this:
One piece of advice: don’t force unwrap here (
date! as Date
). Instead, include a way to handlenil
values for your "optional"NSDate?
variable. One way to do this would look like this:I know this looks like a lot of overhead, but it is worth it to avoid crashes down the line…