class ISHelp: NSObject { internal static let instance = ISHelp() //必须保证init方法的私有性,只有这样,才能保证单例是真正唯一的,避免外部对象通过访问init方法创建单例类的其他实例。由于Swift中的所有对象都是由公共的初始化方法创建的,我们需要重写自己的init方法,并设置其为私有的。 private override init(){ print("create 单例") } //获取当前的年月日 2016-06-15 func getDateStringWithY_M_D() -> (String){ let date:NSDate = NSDate() let dateFormatter:NSDateFormatter = NSDateFormatter.init() dateFormatter.dateFormat = "YYYY-MM-DD" let dateString:String = dateFormatter.stringFromDate(date) return dateString } }
单例调用
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. let help1 = ISHelp.instance let str:String = help1.getDateStringWithY_M_D() print(str) } }原文链接:https://www.f2er.com/swift/323523.html