Swift has a mechanism called extension. It is a very convenient function that you can add functions to existing classes without inheriting the class.
Even if the amount of processing to be implemented in the application to be developed increases, it will be easier to express it with concise code by effectively using the extension. I think that it is a mechanism that must be understood in order to aim for a beginner.
DateExtension.swift
extension Date {
func getDateTimeString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
return dateFormatter.string(from: self)
}
}
If you do this, you will be able to easily get the date string as shown below. It's simpler than implementing the conversion method separately.
datesample.swift
let datestr = Date().getDateTimeString()
This is often the case when you want to display alerts in the view controller. Make it easy with extensions.
UIViewControllerExtension.swift
extension UIViewController {
func displayAlert(title:String, message:String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
You can bring up an alert window with just one line from any view controller.
vcsample.swift
displayAlert(title: "warning", message: "High heat source approach!")
Xcode: 11.7 iOS: 13.7 Swift version: Swift5
that's all
Recommended Posts