Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift equivalent to set multiple values to a property

I am currently using a cocoapod which was written in objective c. In the example they show something like that:

options.allowedSwipeDirections = MDCSwipeDirectionLeft | MDCSwipeDirectionRight;

I don't even know what these sort of variables are called but I already tried the following in Swift:

options.allowedSwipeDirections = MDCSwipeDirection.Left | MDCSwipeDirection.Right

But the compiler says No '|' candidates produce the expected contextual result type 'MDCSwipeDirection'

How would I do this in Swift?

Edit:

It looks like this is not an OptionSet as stated in some answers, her is the declaration:

/*!
 * Contains the directions on which the swipe will be recognized
 * Must be set using a OR operator (like MDCSwipeDirectionUp | MDCSwipeDirectionDown)
 */
@property (nonatomic, assign) MDCSwipeDirection allowedSwipeDirections;

and it is used like that:

_allowedSwipeDirections = MDCSwipeDirectionLeft | MDCSwipeDirectionRight;
like image 324
Ybrin Avatar asked Apr 07 '16 09:04

Ybrin


1 Answers

MDCSwipeDirection is (unfortunately) defined in Objective-C as an NS_ENUM and not as NS_OPTIONS:

typedef NS_ENUM(NSInteger, MDCSwipeDirection) {
    MDCSwipeDirectionNone = 1,
    MDCSwipeDirectionLeft = 2,
    MDCSwipeDirectionRight = 4,
    MDCSwipeDirectionUp = 8,
    MDCSwipeDirectionDown = 16
};

It is therefore imported to Swift as a simple enum and not as an OptionSetType:

public enum MDCSwipeDirection : Int {

    case None = 1
    case Left = 2
    case Right = 4
    case Up = 8
    case Down = 16
}

Therefore you have to juggle with rawValue for enum <-> Int conversions:

let allowedSwipeDirections =  MDCSwipeDirection(rawValue: MDCSwipeDirection.Left.rawValue | MDCSwipeDirection.Right.rawValue)!

Note that the forced unwrap cannot fail, see for example How to determine if undocumented value for NS_ENUM with Swift 1.2:

... Swift 1.2 does now allow the creation of enumeration variables with arbitrary raw values (of the underlying integer type), if the enumeration is imported from an NS_ENUM definition.


If you change the Objective-C definition to

typedef NS_OPTIONS(NSInteger, MDCSwipeDirection) {
    MDCSwipeDirectionNone = 1,
    MDCSwipeDirectionLeft = 2,
    MDCSwipeDirectionRight = 4,
    MDCSwipeDirectionUp = 8,
    MDCSwipeDirectionDown = 16
};

then it is imported as

public struct MDCSwipeDirection : OptionSetType {
    public init(rawValue: Int)

    public static var None: MDCSwipeDirection { get }
    public static var Left: MDCSwipeDirection { get }
    public static var Right: MDCSwipeDirection { get }
    public static var Up: MDCSwipeDirection { get }
    public static var Down: MDCSwipeDirection { get }
}

and you can simply write

let allowedDirections : MDCSwipeDirection = [ .Left, .Right ]
like image 182
Martin R Avatar answered Oct 20 '22 01:10

Martin R