alex
alex

Reputation: 1774

Putting a variable into an UIAlertView - Swift

I created an instance of UIAlertView and named it alert, I did the title and the message, now I'm on addButtonWithTitle. I have tried doing this "Time to wake up it's (strDate)" and I've also tried "Time to wake up" + strDate. Here is the code for the instance of the UIAlertView:

let alert = UIAlertView()
            alert.title = "WAKE UP"
            alert.message = "Time to wake up it's" 
            alert.addButtonWithTitle("I'm Up!")
            alert.show()

On the 3rd line it should say alert.message = "Time to wake up it's strDate"

strDate should be a variable

Here is my strDate

var strDate = timeFormatter.stringFromDate(theDatePicker.date)

Upvotes: 0

Views: 2785

Answers (2)

Mehul Patel
Mehul Patel

Reputation: 23053

Other answer is right but you should use this code:

let alert = UIAlertController(title: "WAKE UP", message:nil, preferredStyle: UIAlertControllerStyle.Alert);
var strDate = "Ok";
alert.message = "Time to wake up " + strDate;


let dismissHandler = {
    (action: UIAlertAction!) in
    self.dismissViewControllerAnimated(true, completion: { () -> Void in
    })
}

alert.addAction(UIAlertAction(title: "I'm Up!", style: .Default, handler: dismissHandler))
presentViewController(alert, animated: true) { () -> Void in
    
}

As per Swift documentation, You should use + operator to add content in a string.

The addition operator is also supported for String concatenation:

"hello, " + "world" // equals "hello, world"

From Swift Programming Language - Basic Operators

Upvotes: 3

Indrajeet
Indrajeet

Reputation: 5666

Try this code, it will help you

alert.message = "Time to wake up it's \(strDate)"

Upvotes: 1

Related Questions