2

In Obj-C, I like to do things like:

[MyUILib makePathForRectWithEdges:UIRectEdgeLeft|UIRectEdgeRight]

In which the argument is an NSInteger, which I later compare to UIRectEdge enum values to see which sides I want to include in the path:

if(edges & UIRectEdgeTop)
{
   // Draw Stuff
}

In Swift, Apple defines UIRectEdge as:

struct UIRectEdge : OptionSetType {
    init(rawValue rawValue: UInt)
    static var None: UIRectEdge { get }
    static var Top: UIRectEdge { get }
    static var Left: UIRectEdge { get }
    static var Bottom: UIRectEdge { get }
    static var Right: UIRectEdge { get }
    static var All: UIRectEdge { get }
}

I can still use UIRectEdge.Top.rawValue to get a UInt, but calling a function like: makePathForRectWithEdges(UIRectEdge.Left.rawValue|UIRectEdge.Right.rawValue) is ugly and hard to read compared to how I used to do it. Is there a better pattern for using flags, or is this just how it has to be in Swift?

GoldenJoe
  • 7,874
  • 7
  • 53
  • 92

1 Answers1

2

Instead of or-ing the raw value, you send a set to the functions:

MyUILib.makePathForRectWithEdges([.Left, .Right])

Hence the name OptionSetType. When you need to check if an option is included in the set:

if edges.contains(.Top) { ... }
Code Different
  • 90,614
  • 16
  • 144
  • 163