gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:34 24 4
gpt4 key购买 nike

目前我正在使用枚举来定义 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com