目前,我正在使用枚举来定义API。我的一个api是发布带有图片或没有图片的笔记。
enum StoreAPI {
...
case newNote(String, Data?) /* note_description, note_image */
}
Run Code Online (Sandbox Code Playgroud)
据我所知,有两种方法:
// 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!
...
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否还有其他方法可以自动解开可选值,或者更好地处理它,或更清晰地处理它。
使用可选的枚举.some绑定:
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
}
Run Code Online (Sandbox Code Playgroud)