MrGuy797
MrGuy797

Reputation: 55

Cannot assign a value of type 'NSDate' to a value of type 'String?'

I am teaching myself swift and I am still very new but I decided to make a simple app that prints the current time when you press a button. the code from the viewcontroller file is as follows:

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    @IBOutlet weak var LblTime: UILabel!
    @IBAction func BtnCalltime(sender: AnyObject) {
            var time = NSDate()
            var formatter = NSDateFormatter()
            formatter.dateFormat = "dd-MM"
            var formatteddate = formatter.stringFromDate(time)
            LblTime.text = time
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

I am having an issue with the line:

LblTime.text = time

I keep getting the error:

Cannot assign a value of type 'NSDate' to a value of type 'String?'

I have tried using:

lblTime.text = time as! string?

And:

lblTime.text = time as! string

but it does still not work, I would be very appreciative of some help. Thanks

Upvotes: 5

Views: 10774

Answers (3)

Joshua Dance
Joshua Dance

Reputation: 10472

Date is now preferred over NSDate. It is an overlay class meaning both will work, but Date but has a lot of advantages, this answer lists some of those.

Here is how to format a date to a string using Date instead of NSDate.

var time = Date()
var formatter = DateFormatter()
formatter.dateFormat = "MMM d yyyy, h:mm:ss a"
let formattedDateInString = formatter.string(from: time)

dateLabel.text = formattedDateInString

A great site to get the formatter strings is http://nsdateformatter.com/ I had no idea that "MMM d yyyy, h:mm:ss a" would equal Mar 1, 7:02:35 AM but the site makes it easy.

Upvotes: 0

Dare
Dare

Reputation: 2587

You made the string from an NSDate already, you just aren't using it.

lblTime.text = formatteddate

Upvotes: 3

Tomáš Linhart
Tomáš Linhart

Reputation: 14299

You need use a value from formatter.

@IBAction func BtnCalltime(sender: AnyObject) {
    var time = NSDate()
    var formatter = NSDateFormatter()
    formatter.dateFormat = "dd-MM"
    var formatteddate = formatter.stringFromDate(time)
    LblTime.text = formatteddate
}

Upvotes: 8

Related Questions