我有一个来自 UILocalNotification 的 userInfo 字典。使用隐式展开时是否有一种简单的方法来获取 String 值?
if let s = userInfo?["ID"]
给我一个必须转换为字符串的 AnyObject。
if let s = userInfo?["ID"] as String
给我一个关于 StringLiteralConvertable 的错误
只是不想声明两个变量来获取字符串 - 一个用于解包,另一个用于转换字符串。
编辑
这是我的方法。这也不起作用 - 我得到 (NSObject, AnyObject) is not conversionble to String on the if statement.
for notification in scheduledNotifications
{
// optional chainging
let userInfo = notification.userInfo
if let id = userInfo?[ "ID" ] as? String
{
println( "Id found: " + id )
}
else
{
println( "ID not found" )
}
}
我的问题中没有它,但除了让这种方式工作之外,我还想拥有
if let s = notification.userInfo?["ID"] as String
最佳答案
您想通过 as?
使用条件转换:
(注意:这适用于 Xcode 6.1。对于 Xcode 6.0,请参见下文)
if let s = userInfo?["ID"] as? String {
// When we get here, we know "ID" is a valid key
// and that the value is a String.
}
此构造从 userInfo
中安全地提取字符串:
如果
userInfo
为nil
,userInfo?["ID"]
返回nil
,因为可选链接 和条件转换 返回一个String?
类型的变量,其值为nil
。然后,可选绑定(bind) 失败,并且未输入该 block 。如果
"ID"
不是字典中的有效键,userInfo?["ID"]
返回nil
并且它像前一个案例一样进行。如果值是另一种类型(如
Int
),则条件转换as?
将返回nil
和上面的案例一样。最后,如果
userInfo
不为nil
,并且"ID"
是字典中的有效键,则类型该值的一部分是一个String
,然后 条件转换 返回一个包含该字符串的可选字符串String?
。 可选绑定(bind)if let
然后打开String
并将其分配给类型为String 的
.s
对于 Xcode 6.0,您还必须做一件额外的事情。您需要有条件地转换为 NSString
而不是 String
因为 NSString
是对象类型而 String
不是。他们显然改进了 Xcode 6.1 中的处理方式,但对于 Xcode 6.0,请执行以下操作:
if let s:String = userInfo?["ID"] as? NSString {
// When we get here, we know "ID" is a valid key
// and that the value is a String.
}
最后,解决您的最后一点:
for notification in scheduledNotifications
{
if let id:String = notification.userInfo?["ID"] as? NSString
{
println( "Id found: " + id )
}
else
{
println( "ID not found" )
}
}
关于dictionary - 从 userInfo 字典中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26331673/