Nassif
Nassif

Reputation: 1223

Constant Declaration in swift

I have a constant string defined as

#define kNotificationMessage @"It's time to take your %@"

In objective C i use

[NSString stringWithFormat:kNotificationMessage, medicineString]

as the message to the UIAlertView . How do we achieve this in swift

Upvotes: 3

Views: 1133

Answers (6)

Nithin
Nithin

Reputation: 6475

First create a struct

struct AStructConstants 
{
    static let sampleString : NSString = NSString(string: "Check out what I learned about %@ from Stackoverflow.")
}

var aString : NSString = NSString(format: AStructConstants.sampleString, "some custom text")
println(aString)

Your output would be:

Check out what I learned about some custom text from Stackoverflow.

Upvotes: -2

Yu Yu
Yu Yu

Reputation: 1369

let msg = "It's time to take your" as String

let alertController = UIAlertController(title: "iOScreator", message:

        "\(msg)" , preferredStyle: UIAlertControllerStyle.Alert)

    alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))

    self.presentViewController(alertController, animated: true, completion: nil)

That is how I do alert in Swift. If I didn't understand wrongly and this code is useful for you, I will be glad. :)

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236558

let medicineString = "analgesic"
let kNotificationMessage = "It's time to take your %@"

let sentence = String(format: kNotificationMessage, medicineString)

println(sentence) // It's time to take your analgesic"

Upvotes: 7

chenzhongpu
chenzhongpu

Reputation: 6871

You'd better to deal with such constant using struct:

struct GlobalConstants {
    static let kNotificationMessage = "It's time to take your"
}

println(GlobalConstants.kNotificationMessage)

Upvotes: 0

John Rogers
John Rogers

Reputation: 2202

You can't. You're going to have to make a function out of it:

func notificationMessage(medicineString: String) -> String {
    return "It's time to take your " + medicineString
}

For more information, this thread is quite a good read.

Upvotes: 0

Nimit Parekh
Nimit Parekh

Reputation: 16864

Please use following code may be solve your problem.

let kNotificationMessage:String = "It's time to take your %@"
var modifiedString = NSString(format:kNotificationMessage:String, medicineString) as String

Upvotes: 2

Related Questions