# 20.Swift位移枚举

## 一：以系统中的一个位移枚举为例

### a. OC版本

```Swift
typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
    UIRectCornerTopLeft     = 1 << 0,
    UIRectCornerTopRight    = 1 << 1,
    UIRectCornerBottomLeft  = 1 << 2,
    UIRectCornerBottomRight = 1 << 3,
    UIRectCornerAllCorners  = ~0UL
};
```

```Swift
[view addRoundedCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) withRadii:CGSizeMake(12.f, 12.f)];
```

### b.Swift版本

```Swift
public struct UIRectCorner : OptionSet {
    public init(rawValue: UInt)
    
    public static var topLeft: UIRectCorner { get }

    public static var topRight: UIRectCorner { get }

    public static var bottomLeft: UIRectCorner { get }

    public static var bottomRight: UIRectCorner { get }

    public static var allCorners: UIRectCorner { get }
}
```

```Swift
$0.addRoundedCorners([.topLeft, .topRight], withRadii: CGSize(width: 15, height: 15))
```

### c.分析

发现在Swift中它并不是枚举，而是装换为了`结构体`，使用的API出则是转换为了对应元素类型的数组。 我们需要自定义位移枚举的时候可以参考系统的这种实现方式。

**如：**

```Swift
struct Sports: OptionSet {
    let rawValue: Int

    static let running = Sports(rawValue: 1)
    static let cycling = Sports(rawValue: 2)
    static let swimming = Sports(rawValue: 4)
    static let fencing = Sports(rawValue: 8)
    static let shooting = Sports(rawValue: 32)
    static let horseJumping = Sports(rawValue: 512)
}
```

## 二：Swift:union

当然部分API并没有经过上面的这种转化，如： 下面就是我在异步处理图片的时候遇到的一个场景

```Swift
let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: hasAlpha ? CGImageAlphaInfo.premultipliedFirst.rawValue : CGImageAlphaInfo.noneSkipFirst.rawValue).union(.byteOrder32Little)
```

正如注释中所说：`A new option set made up of the elements contained in this set, in other, or in both.`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/swift/swift-wei-yi-mei-ju.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
