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