if let s = userInfo?["ID"]
给我一个AnyObject,我必须强制转换为字符串.
if let s = userInfo?["ID"] as String
给我一个关于StringLiteralConvertable的错误
只是不想声明两个变量来获取字符串 – 一个用于解包的文字和另一个用于转换字符串的var.
编辑
这是我的方法.这也不起作用 – 我得到(NSObject,AnyObject)在if语句中不能转换为String.
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
解决方法
(注意:这适用于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类型的变量?它的值为零.然后,可选绑定失败,并且未输入块.
>如果“ID”不是字典中的有效键,userInfo?[“ID”]返回nil,它会像前一种情况一样继续.
>如果值是另一种类型(如Int),则条件转换为?将返回零,并像上述情况一样继续.
>最后,如果userInfo不是nil,并且“ID”是字典中的有效键,并且值的类型是String,则条件转换返回可选字符串String?包含字符串.可选绑定如果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" ) } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。