robdashnash robdashnash - 7 months ago 14
Swift Question

Swift avoid repeating code in initializer

How can I avoid repeating code between my initialisers? I want the dateFormatter to remain a let constant.

let dateFormatter: NSDateFormatter

init() {
dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .MediumStyle
super.init(nibName: nil, bundle: nil)
}

required init?(coder aDecoder: NSCoder) {
dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .MediumStyle
super.init(coder: aDecoder)
}

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .MediumStyle
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}

Answer

If this is really the actual code replace the entire code with

lazy var dateFormatter : NSDateFormatter = {
   let formatter = NSDateFormatter()
   formatter.dateStyle = .MediumStyle
   formatter.timeStyle = .MediumStyle
   return formatter
}()

The variable is lazily initialized once when it's accessed the first time

Edit: It's also possible to declare the variable as constant without the lazy attribute.

let dateFormatter : NSDateFormatter = { ...

The difference is that the formatter is created immediately (not lazily) during the initialization of the instance.

Comments