Michael
Michael

Reputation: 33297

NSDictionary representation in Swift

From CRToast I want to write the following in Swift (This is from the 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");
                            }];

Here is my Swift representation of the first few lines:

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

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

When I compile and run the code I got the following error:

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

What is the correct translation of the NSDictionary presented above in Swift?

Upvotes: 0

Views: 700

Answers (2)

The API you are using apparently expects that the value for the text alignment enum be specified as an NSNumber, and not as a string. (that's not surprising - enums are integers in (Objective-)C.)

So, instead of using string interpolation, make an NSNumber out of the enum's value:

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

By the way, you don't need all those assignments. That's exactly the point in using a dictionary literal. You don't need to make the dictionary mutable then. Just do this:

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

Upvotes: 1

Antonio
Antonio

Reputation: 72750

NSTextAlignment.Center is an enum, internally represented as an integer - but you are passing it as a string:

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

whereas you should use the enum raw value:

options[kCRToastTextAlignmentKey] = NSTextAlignment.Center.rawValue

Upvotes: 5

Related Questions