Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/116.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios swift中的常量声明_Ios_Objective C_Xcode_Swift - Fatal编程技术网

Ios swift中的常量声明

Ios swift中的常量声明,ios,objective-c,xcode,swift,Ios,Objective C,Xcode,Swift,我有一个常量字符串,定义为 #define kNotificationMessage @"It's time to take your %@" 在目标C中,我使用 [NSString stringWithFormat:kNotificationMessage, medicineString] 作为发送到UIAlertView的消息。我们如何在swift中实现这一点?首先创建一个结构 struct AStructConstants { static let sampleString

我有一个常量字符串,定义为

#define kNotificationMessage @"It's time to take your %@"
在目标C中,我使用

[NSString stringWithFormat:kNotificationMessage, medicineString]
作为发送到UIAlertView的消息。我们如何在swift中实现这一点?首先创建一个结构

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)
您的输出将是:

查看我从Stackoverflow中学到的一些自定义文本


请使用以下代码可能会解决您的问题

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

你不能。你必须用它来做一个函数:

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

有关更多信息,请参阅。

您最好使用
struct
处理此类常量:

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

println(GlobalConstants.kNotificationMessage)

这就是我在斯威夫特的警觉方式。如果我没有理解错,并且此代码对您有用,我将很高兴。:)

您想将此用于uialertview吗?只需使用“let”变量下面这个问题有一些非常奇怪和非常错误的答案(包括公认的答案)。等效的Swift代码是
let kNotificationMessage=“查看我从Stackoverflow中学到的%@知识。”;设aString=String(格式:kNotificationMessage,medicineString)
Swift本机类型为String而非NSString。您应该使用let aString=“无论如何”。顺便说一句,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"
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)