enum Media {
case image
case video
}
struct UploadManager {
static func upload(mediaType: Media, data: AnyObject, completion: Response -> Void) {
switch mediaType {
case .image:
uploadImage(data as? UIImage, completion: completion)
case .video:
uploadVideo(data as? NSURL, completion: completion)
}
}
static func uploadImage(image: UIImage, completion: Response -> Void ) {
let imageData = UIImagePNGRepresentation(image)! as NSData
let options = ["resourcetype": "image"]
//API call
}
static func uploadVideo(filePath: NSURL, completion: Response -> Void ) {
let options = ["resourcetype": "video"]
//API call
}
}
示例通话将是:
UploadManager.upload(.image, data: data, completion: {
})
这里我使用.image类型和数据向UploadManager发出请求。我担心的是图像和数据是互斥的,容易出错。说,我通过了.image而不是.video,而向下转发会导致崩溃。任何方式来处理这个问题
答案 0 :(得分:1)
您可以在枚举中嵌入数据。例如:
enum Media {
case Image(image: UIImage)
case Video(url: NSURL)
}
您可以在match-case
:
static func upload(media: Media, completion: Response -> Void) {
switch media {
case .Image(let image):
uploadImage(image, completion: completion)
case .Video(let url):
uploadVideo(url, completion: completion)
}
}
然后,你可以这样调用这个方法:
let image = UIImage()
UploadManager.upload(.Image(image)) { response in
print("Upload complete!")
}