我可以使用Int从Swift设置Int enum类型的Objective-C属性

时间:2016-03-04 20:18:15

标签: swift enums

我有一个Objective-C对象,其属性类型为VerticalAlignmentVerticalAlignment是枚举,由整数支持:

typedef NS_ENUM(unsigned int, VerticalAlignment)
{
   kVerticallyAlignMiddle = 0,
   kVerticallyAlignTop,
   kVerticallyAlignBottom
};

@property VerticalAlignment alignment;

我想从Swift对象设置alignment

if let textGraphic = internalTextGraphic {
   textGraphic.alignment.rawValue = newValue
}

但我rawValue是不可改变的。

有什么方法可以传递alignment一个整数来设置?

1 个答案:

答案 0 :(得分:1)

textGraphic.alignment = VerticalAlignment(rawValue: newRawValue)!

请注意,VerticalAlignment.init(rawValue:)会返回Optional<VerticalAlignment>,如果原始值无效,则为{n}。所以如果你传递了一个伪造的newRawValue,程序会在试图解开nil时崩溃。如果你想避免这种情况:

textGraphic.alignment = VerticalAlignment(rawValue: newRawValue) ?? textGraphic.alignment

if let alignment = VerticalAlignment(rawValue: newRawValue) {
    textGraphic.alignment = alignment
}