[Swift] Let's use extension

Introduction

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.

Example 1: Add a method to generate a date string to Date type

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()

Example 2: Added a method to display an alert in the view controller.

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!")

Operation check environment

Xcode: 11.7 iOS: 13.7 Swift version: Swift5

that's all

Recommended Posts

[Swift] Let's use extension
[Swift] Let's use Segmented Control
Let's use Swift Firebase Firebase Auth
Swift extension collection
Let's use Swift Package Manager (SwiftPM) ~ Creation ~
Let's use Swift Package Manager (SwiftPM) ~ Introduction ~
[Swift] About protocol extension
[spring] Let's use Spring Data JPA
Use Swift Package on Playground
[Swift] How to use UserDefaults
How to use Swift UIScrollView
[Swift UI] Use Map view
Let's use Set more [Collections Framework]
[Swift] Another way to use Result?
Let's use Twilio in Java! (Introduction)
Let's use Amazon Textract with Ruby
Let's use reflection Private method access
Let's use it after understanding sudo!
[Swift] How to use SwiftLint (cocoapods)
[Swift] How to use Unwind segue
Install Xcode and use Hello Swift!
[Swift] How to use Tab Bar Controller
[Swift / Beginner] Use Enum for maintainable coding
[Swift] How to use one option alert