Koichi Adachi

smart phone app development tips

pass a enum key Dictionary to Swift from ObjC

expect receive enum-key dict (Dictionary<EnumType,T>) from Objective-C. but can't receive direct EnumType key because XCode abandon generate method.

ObjC's NSDictionary not allow Int for key. to use instead of NSNumber.

definition in swift

@objc public enum HogeType:Int{
  case unknown
  case hoge1
  case hoge2
  case hoge3
  case hoge4
  case hoge5

public class A{
public class func wantToTreatMethod(dictionary:Dictionary<Int, String>){
  //TODO:convert Dictionary<Int, String> to Dictionary<HogeType, String>
  // next article.

auto converted in ObjC

typedef SWIFT_ENUM(NSInteger, HogeType) {
  HogeTypeUnknown = 0,
  HogeType1 = 1,
  HogeType2 = 2,
  HogeType3 = 3,
  HogeType4 = 4,
  HogeType5 = 5,

@interface A : NSObject
+ (void)wantToTreatMethod:(NSDictionary<NSNumber *, NSString *> * _Nonnull)dict; //key type is Int in Swift, It was not made this method.

invoke from ObjC

NSDictionary<NSNumber*, NSString*> *dict
     = @{@(HogeTypeHoge1) : @"a",
         @(HogeTypeHoge2) : @"b",
         @(HogeTypeHoge3) : @"c",
         @(HogeTypeHoge4) : @"d",
         @(HogeTypeHoge5) : @"e"};

[A wantToTreatMethod:dict];