Eco Apps Eco Apps - 1 year ago 78
Swift Question

Issue with including NSDateFormatter in a class

I am trying to add time in my Note Class but getting an error message.

What is the correct way to include time on note entry in a class?

Here are the error message inline commented:

class noteTime{
var timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "h:mm a" //ERROR: Expected Declaration
timeFormatter.AMSymbol = "AM"
timeFormatter.PMSymbol = "PM"

var timeString = timeFormatter.stringFromDate(NSDate())
//ERROR: Instance member 'timeFormatter' cannot be used on type 'noteTime'

Answer Source

To get a timestamp use a closure to assign the value.

class NoteTime { // class names are supposed to start with a capital letter

  let timeString : String  = {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "h:mm a"
    formatter.AMSymbol = "AM"
    formatter.PMSymbol = "PM"
    return formatter.stringFromDate(NSDate())

Now each time an instance is created the timestamp is saved as constant (let!) in timeString.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download