19

I writing this code in swift and Xcode 6

@IBAction func Alert(sender : UIButton) {
  var alert : UIAlertView = UIAlertView(title: "Hey", message: "This is  one Alert",       delegate: nil, cancelButtonTitle: "Working!!")

    alert.show()
}

Xcode doesn't show error in compilation.

but in Simulator the APP fails and return the error:

(lldb)
thread 1 EXC_BAD_ACCESS(code 1 address=0x20)
dandan78
  • 13,328
  • 13
  • 64
  • 78
rickdecard
  • 211
  • 1
  • 2
  • 5

1 Answers1

46

There is a bug in the Swift shim of the UIAlertView convenience initializer, you need to use the plain initializer

let alert = UIAlertView()
alert.title = "Hey"
alert.message = "This is  one Alert"
alert.addButtonWithTitle("Working!!")
alert.show()

This style code feels more true to the Swift Language. The convenience initializer seems more Objective-C'ish to me. Just my opinion.

Note: UIAlertView is deprecated (see declaration) but Swift supports iOS7 and you can not use UIAlertController on iOS 7

View of UIAlertView Declaration in Xcode

// UIAlertView is deprecated. Use UIAlertController with a preferredStyle of   UIAlertControllerStyleAlert instead
class UIAlertView : UIView {

An Alert in Swift iOS 8 Only

var alert = UIAlertController(title: "Hey", message: "This is  one Alert", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Working!!", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

Update for Swift 4.2

let alert = UIAlertController(title: "Hey", message: "This is  one Alert", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Working!!", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
GayleDDS
  • 4,443
  • 22
  • 23