简体   繁体   中英

How to box int (enum) to object in swift?

I need to cast an int to an object, in Objective-C I could do the following

[row.cellConfig setObject:@(UITextFieldViewModeAlways) forKey:@"textField.rightViewMode"];

What would be the Swift equivalent?

The Swift equivalent of UITextFieldViewModeAlways is UITextFieldViewMode.Always , which is an enumeration value:

enum UITextFieldViewMode : Int {
    case Never
    case WhileEditing
    case UnlessEditing
    case Always
}

You get its underlying integer value with .rawValue . Integers are automatically "bridged" to NSNumber when passed to functions taking Objective-C parameters (and Swift strings bridged to NSString ).

So this should work:

row.cellConfig.setObject(UITextFieldViewMode.Always.rawValue,
                forKey: "textField.rightViewMode")

For more information, see Using Swift with Cocoa and Objective-C .

采用

row.cellConfig.setObject(NSNumber(UITextFieldViewModeAlways), forKey:"textField.rightViewMode")

您需要为该int创建一个NSNumber对象。

NSNumber *intObj = [NSNumber numberWithInt:num];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM