Home > Back-end >  Cannot find the right logic to translate the NSDate to string
Cannot find the right logic to translate the NSDate to string

Time:01-21

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?'

CodePudding user response:

You are printing the correct String value, but assigning the variable date which typed as NSDate? to the text property, which should be a String.

Try doing this:

let dateString = dateFormatterPrint.string(from: date! as Date)
cell.perditsuarOutlet.text = dateString

One piece of advice: don't force unwrap here (date! as Date). Instead, include a way to handle nil values for your "optional" NSDate? variable. One way to do this would look like this:

if let date = dateFormatterGet.date(from: currentVechicle.LastCommunicationDate!) as NSDate? {
  cell.perditsuarOutlet.text = dateFormatterPrint.string(from: date as Date)
} else {
  cell.perditsuarOutlet.text = "Empty or invalid date"
}

I know this looks like a lot of overhead, but it is worth it to avoid crashes down the line...

CodePudding user response:

  • 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 :)

  •  Tags:  
  • Related