Swift中的NSDictionary表示

时间:2015-04-16 15:14:59

标签: ios objective-c swift

CRToast我想在Swift中写下以下内容(这是来自CRToast example):

NSDictionary *options = @{
                          kCRToastTextKey : @"Hello World!",
                          kCRToastTextAlignmentKey : @(NSTextAlignmentCenter),
                          kCRToastBackgroundColorKey : [UIColor redColor],
                          kCRToastAnimationInTypeKey : @(CRToastAnimationTypeGravity),
                          kCRToastAnimationOutTypeKey : @(CRToastAnimationTypeGravity),
                          kCRToastAnimationInDirectionKey : @(CRToastAnimationDirectionLeft),
                          kCRToastAnimationOutDirectionKey : @(CRToastAnimationDirectionRight)
                          };

[CRToastManager showNotificationWithOptions:options
                            completionBlock:^{
                                NSLog(@"Completed");
                            }];

这是我前几行的Swift表示:

var options:[NSObject:AnyObject] = [:]
options[kCRToastTextKey] = "Hello World !"
options[kCRToastTextAlignmentKey] = "\(NSTextAlignment.Center)"
options[kCRToastBackgroundColorKey] = UIColor.redColor()

CRToastManager.showNotificationWithOptions(options, completionBlock: { () -> Void in
      println("done!")
    })

当我编译并运行代码时,我收到以下错误:

[CRToast] : ERROR given (Enum Value) for key kCRToastTextAlignmentKey was expecting Class __NSCFNumber but got Class Swift._NSContiguousString, passing default on instead

上面在Swift中提供的NSDictionary的正确翻译是什么?

2 个答案:

答案 0 :(得分:5)

NSTextAlignment.Center是一个枚举,内部表示为整数 - 但是你将它作为字符串传递:

options[kCRToastTextAlignmentKey] = "\(NSTextAlignment.Center)"

而你应该使用枚举原始值:

options[kCRToastTextAlignmentKey] = NSTextAlignment.Center.rawValue

答案 1 :(得分:1)

您正在使用的API显然希望将文本对齐枚举的值指定为NSNumber,而不是字符串。 (这并不奇怪 - 枚举是(目标 - )C中的整数。)

因此,不是使用字符串插值,而是从枚举值中取出NSNumber:

options[kCRToastTextAlignmentKey] = NSNumber(integer: NSTextAlignment.Center.rawValue)

顺便说一下,你不需要所有这些作业。这正是使用字典文字的重点。您不需要使字典可变。就这样做:

let options:[NSObject:AnyObject] = [
  kCRToastTextKey: "Hello World !",
  kCRToastTextAlignmentKey: NSNumber(integer: NSTextAlignment.Center.rawValue),
  kCRToastBackgroundColorKey: UIColor.redColor()
]