swift - 在枚举中自动展开可选属性

标签 swift enums

目前我正在使用枚举来定义 API。我的一个 API 正在发布一 strip 有或不带有图像的注释。

enum StoreAPI {
    ...
    case newNote(String, Data?) /* note_description, note_image */
}

据我所知,处理这种情况有两种方法:

// Option 1
switch api {
...
case let newNote(description, imageData):
   if let imageData = imageData {
       // Post with image
   }
   else {
      // Post without image
   }
...
}

// Option 2
switch api {
    ...
    case let newNote(description, nil):
       // Post without image
    case let newNote(description, imageData):
       let imageData = imageData!
    ...
}

我想知道是否有任何其他方法可以自动解包可选值,或者更好地处理它,或者更清楚。

最佳答案

使用可选枚举的 .some 绑定(bind):

enum StoreAPI {
    case newNote(String, Data?)
}

// sample data
let api = StoreAPI.newNote("title", "data".data(using: .utf8))

switch api {

case let .newNote(title, .some(data)):
    print("title: \(title), data: \(data)")

default:
    break

}

关于swift - 在枚举中自动展开可选属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43448111/

相关文章:

ios - Collection View 单元格内的 MKMapview 不可见

macos - 如何检测弹出窗口是否已完成?

ios - 在某些选项卡上选择时,选项卡栏背景会更改颜色

swift - 为什么具有可选关联值的 Swift 枚举在声明时需要尾随括号?

python-3.x - Python 3 枚举元组相等总是失败

Java Spring 无法创建使用枚举作为构造函数参数的 Bean

ios - Swift playgrounds ios 10 文字转语音命令代码

ios - 我们想在我们自己的服务器上使用 Rocket.chat 而不是 open.rocket.chat 一些我们无法继续的事情

c# - 有没有办法使 ToEnum 通用

java - 具有属性的 UML 建模枚举