Get top most UIViewController in Swift

To get the topmost view controller in Swift you need to take into account the presented viewcontrollers. This can be achieved in the following ways

        if var controller = window.rootViewController {
            while let presentedViewController = controller.presentedViewController {
                controller = presentedViewController
            }
          // controller is the topmost one
        } else {
            fatalError()
        }

You also need to take into account iOS 13 + versions

let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first

if var controller = keyWindow?.rootViewController {
    while let presentedViewController = topController.presentedViewController {
        controller = presentedViewController
    }

// controller is the topmost one
}

Happy coding !!!

A pat on the back !!