简体   繁体   English

迅速的不断宣言

[英]Constant Declaration in swift

I have a constant string defined as 我有一个常量字符串定义为

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

In objective C i use 在目标C我使用

[NSString stringWithFormat:kNotificationMessage, medicineString]

as the message to the UIAlertView . 作为UIAlertView的消息。 How do we achieve this in swift 我们如何迅速实现这一目标

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"

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
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. 这就是我在Swift中提醒的方式。 If I didn't understand wrongly and this code is useful for you, I will be glad. 如果我不理解并且这段代码对你有用,我会很高兴的。 :) :)

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. 有关更多信息, 此线程是一个很好的阅读。

You'd better to deal with such constant using struct : 你最好处理这样的常量使用struct

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

println(GlobalConstants.kNotificationMessage)

First create a struct 首先创建一个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. 看看我从Stackoverflow中学到了一些自定义文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM