0
我想创建一个NSNumber对象。 我有这个代码在objc:Swift 3创建一个NSNumber对象
@property (nonatomic, assign) Enum someEnum;
static NSString *const value_type = @"type";
- (id)initWithDictionary:(NSDictionary *)dict andUID:(int)uid {
self.someEnum = [[dict objectForKey:value_type] integerValue];
}
- (NSDictionary *)serializeToDictionary {
dict[value_type] = [NSNumber numberWithInteger:self.someEnum];
}
如何此代码将在迅速3等价? 我发现在swift NSNumber中有init(value:)符号,但它只是初始化一个对象,而不是创建和初始化。而且init(value:)会抛出一个错误,这表明将“value”改为“coder”。 我的银行代码:
var someEnum = Enum.self
let value_type: NSString = "type"
init(dictionary dict: NSDictionary, andUID uid: Int) {
self.someEnum = dict.object(forKey: value_type) as! Enum.Type
}
func serializeToDictionary() -> NSDictionary {
dict[value_type] = NSNumber.init(value: self.someEnum)
}
Objective-C的头文件:
typedef enum {
EnumDefault = 0,
EnumSecond = 1
} Enum;
static NSString *const value_type = @"type";
@property (nonatomic, assign) Enum someEnum;
目标C实现文件:
- (id)initWithDictionary:(NSDictionary *)dict andUID:(int)uid {
if(self = [super init]) {
self.someEnum = [[dict objectForKey:value_type] integerValue];
}
return self
}
- (NSDictionary *)serializeToDictionary {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[value_type] = [NSNumber numberWithInteger:self.someEnum];
return dict;
}
My Enum是Int类型。我试过你的代码,但它说 - 无法将类型“Class.Enum.RawValue.Type(又名Int.Type)的值转换为在强制中键入NSNumber –
@KasparsLapins您是否在顶部获得”第一个错误“注释? – Sulthan
项目使用此代码编译,但它做同样的事情吗?dict [value_type] = self.someEnum.rawValue()作为NSNumber –