简体   繁体   中英

Accessing NS_OPTIONS in swift option unavailable

I defined an NS_OPTIONS in Objective-C .h file:

typedef NS_OPTIONS (NSInteger, Options){
    OptionsOne,
    OptionsTwo,
    OptionsThree
};

Now when accessing from Swift:

public func myFunc() -> Options {
    return [.one, .two]
}

I am getting this error:

'one' is unavailable: use [] to construct an empty option set.

But I am not getting this error for .two or .three. It appears only for the first option.

By default, in Swift 3, an NS_OPTIONS enumerand equating to 0 is not imported into Swift by name. You have to use [] in Swift to get it.

When you changed the enumerand's value to 1 , the name was imported.

If you think about it, this makes perfect sense. NS_OPTIONS is for bitmasks. Thus, if (let's say) .one is 0 and .two is 1 , there is no useful meaning to the expression [.one, .two] because there is no information added by the presence of the .one .

What you were doing, on the other hand, was always a misuse of NS_OPTIONS , since it was not a bitmask. Your modification turned it into one. (Objective-C does not magically generate bitmask-appropriate values for you.)

I have found the solution to this to be adding explicit bitmask value to the options:

typedef NS_OPTIONS (NSInteger, Options){
    OptionsOne = 1 << 0,
    OptionsTwo = 1 << 1,
    OptionsThree = = 1 << 2
};

and the error went away.

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