我有以下Objective-C代码:
NSMutableDictionary *options = // some values
options[kCRToastInteractionRespondersKey] =
@[[CRToastInteractionResponder interactionResponderWithInteractionType:CRToastInteractionTypeTap
automaticallyDismiss:YES
block:^(CRToastInteractionType interactionType){
NSLog(@"Dismissed with %@ interaction",
NSStringFromCRToastInteractionType(interactionType));
}]];
我想在Swift中创建等价物:
var options:[NSObject:AnyObject] = [:]
options[kCRToastInteractionRespondersKey] = CRToastInteractionResponder(interactionType: CRToastInteractionType.Tap, automaticallyDismiss: true) { (r:CRToastInteractionType) -> Void in }
当我运行代码时,我收到错误:
ERROR given <CRToastInteractionResponder: 0x7b9e2cd0> for key kCRToastInteractionRespondersKey was expecting Class NSArray but got Class CRToastInteractionResponder, passing default on instead
如何在Swift中将CRToastInteractionResponder
正确添加到NSDictionary中?
修改
我也试过
var options:NSDictionary = [:]
但是当我使用以下命令调用它时,我必须将选项投射到[NSObject : AnyObject]
CRToastManager.showNotificationWithOptions(options as [NSObject : AnyObject], completionBlock: { () -> Void in
println("done!")
})
错误仍然相同。
答案 0 :(得分:1)
我认为这是解决方案:
var options:[NSObject:AnyObject] = [:]
options[kCRToastInteractionRespondersKey] = [CRToastInteractionResponder(interactionType: CRToastInteractionType.Tap, automaticallyDismiss: true) { (r:CRToastInteractionType) -> Void in }]
答案 1 :(得分:0)
NSDictionary在初始化时可以有对象,因此在初始化后无法添加对象。
所以你需要NSMutableDictionary。
你可以写
var options:NSMutableDictionary = NSMutableDictionary()
options .setObject("your object to store", forKey: kCRToastInteractionRespondersKey)
或者您可以将块的结果存储在 var 中,然后将其添加到字典中。
希望这会对你有所帮助。