Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 397
MrGuy797 Avatar asked Jul 14 '15 20:07

MrGuy797


2 Answers

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
}
like image 140
Tomáš Linhart Avatar answered Nov 20 '22 06:11

Tomáš Linhart


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

lblTime.text = formatteddate
like image 37
Dare Avatar answered Nov 20 '22 06:11

Dare