How to display alert message in Swift 3

Last Updated: October 12, 2017

To display the Alert message in your Swift 3 application you can use the following code
I am using UIAlertController to show the message

let msg : String="How are you?"
        
let alert = UIAlertController(title: "Hello", message: msg, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)

You can see the following alert window for the above code

alert window swift

 

If you want to add “OK” button for the alert window you can use the following code

let alert = UIAlertController(title: "Hello", message: msg, preferredStyle: UIAlertControllerStyle.alert)
// add OK button
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)

You will get the following alert window with “Ok” button

Alert window with ok swift

Test