从userInfo Dictionary获取字符串
我有来自UILocalNotification的userInfo字典.使用隐式展开时是否有一种简单的方法来获取String值?
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 解决方法
你想使用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类型的变量?它的值为零.然后,可选绑定失败,并且未输入块. 对于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" ) } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |