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 –