As stated in the title, how to convert [AnyHashable: Any] to nsmutabledictionary? I need to do some Obj-c to Swift relation.
CodePudding user response:
It is very straight forward
var d = [AnyHashable: Any]()
d["name"] = "Jay"
d[0] = "Jay"
print(d)
//[AnyHashable(0): "Jay", AnyHashable("name"): "Jay"]
let nsD = NSDictionary(dictionary: d)
print(nsD)
//{
// 0 = Jay;
// name = Jay;
//}
let nsMD = NSMutableDictionary(dictionary: d)
print(nsMD)
//{
// 0 = Jay;
// name = Jay;
//}
Bridging example:
Your swift class may look like this
@objc class Swft: NSObject {
@objc var d = [AnyHashable: Any]()
override init() {
super.init()
d["name"] = "jay"
}
@objc func method() ->[AnyHashable: Any] {
return d
}
}
And your Objective-C class may look like this, .m
#import "Objc.h"
#import "{Your_project_name}-Swift.h"
@interface Objc ()
@end
@implementation Objc
- (void)someMethod {
Swft *s = [[Swft alloc] init];
NSLog(@"1234567890 %@", s.d);
// 1234567890 {
// name = jay;
// }
NSLog(@"0987654321 %@", [s method]);
// 0987654321 {
// name = jay;
// }
}
@end