Saving the selection of UISegmentedControl (Swift 4.x-5.x)

It happens that you need to save the previously selected value in the UISegmentedControl. Below is this solution for Swift 4.x-5.0 which I use in my application.

It would seem that there is difficult? After all, you just need to save the previously selected value. But just such a small function includes all the code below.

class ViewController: UIViewController {

    @IBOutlet weak var segmentedControl: UISegmentedControl!

    @IBAction func segmentSelected(_ sender: UISegmentedControl) {

        UserDefaults.standard.set(sender.selectedSegmentIndex, forKey: "chosenOption")

    override func viewDidLoad() {

        if let value = UserDefaults.standard.value(forKey: "chosenOption"){
            let selectedIndex = value as! Int
            segmentedControl.selectedSegmentIndex = selectedIndex