When Extension means Shorten Code

When coding in Swift, one of the most frequently used function is to convert Date to String. There are many ways to do that.
The most beginner way I can think of the this …
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let dateString = formatter.string(from: date)But if you have to write this 4 lines of code every single time you want to format a Date() , that is very pain, right? So, as a good developer, you will probably put it inside a function. like this …
func formatDate(_ date: Date, for format: String) -> String{
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: date)
}and call the function formatDate(date, for: "yyyy-MM-dd") . Ok, that save you some code. But what if you want to use this function in all Classes in your project. Well… you will create an DateFormat class and on and on and on…right? ah..no. In Swift, there are Extensions. It will save you ton of codes. Basically, extensions allows you to “plug” your functions in to any classes. To use the extension, you just need to wrap your function in side an extension {}, like the following …
extension Date {
func formatDate(_ format: String = "yyyy-MM-dd") -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: self)
}
}And you will call the function with your Date() variables. like this…
Date().formatDate() //2018-09-09That’s it. If you want to use other format, you can use the same function but pass the a format String to it. like this…
Date().formatDate("yyyy-MM-dd hh:mm:ss") //2018-09-09 12:13:59Oh, I just accidentally showed you how default parameter works in Swift. Well. I think this is enough for me to convince you how extension can shorten you code. I mean by a lot.
