2017-03-09 60 views
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; 
} 

回答

1
var someEnum = Enum.self 

someEnum的值是一個類型,而不是一個具體的價值。這是你的第一個錯誤。

你想大概就像

var someEnum: Enum = ... // (your default value) 

現在

dict[value_type] = NSNumber.init(value: self.someEnum) 

枚舉不會自動轉換爲整數。假設EnumInt值(對所有枚舉不是這樣)支持。比你可以使用:

dict[value_type] = NSNumber(value: self.someEnum.rawValue) 

或只是

dict[value_type] = self.someEnum.rawValue as NSNumber 

的完整代碼(它不是在斯威夫特和我使用!應該更好地解決解決特殊狀態中使用NS(Mutable)Dictionary一個好主意)。

enum Enum : Int { 
    case `default` = 0 
    case second = 1 
} 

class Test { 
    var someEnum: Enum = .default 
    let valueType: String = "type" 

    init(dictionary: NSDictionary, andUID uid: Int) { 
     self.someEnum = Enum(rawValue: (dictionary[valueType] as! NSNumber).intValue) ?? .default 
    } 

    func serializeToDictionary() -> NSDictionary { 
     let dictionary = NSMutableDictionary() 
     dictionary[valueType] = self.someEnum.rawValue as NSNumber 

     return dictionary 
    } 
} 
+0

My Enum是Int類型。我試過你的代碼,但它說 - 無法將類型「Class.Enum.RawValue.Type(又名Int.Type)的值轉換爲在強制中鍵入NSNumber –

+0

@KasparsLapins您是否在頂部獲得」第一個錯誤「註釋? – Sulthan

+0

項目使用此代碼編譯,但它做同樣的事情嗎?dict [value_type] = self.someEnum.rawValue()作爲NSNumber –