2016-08-08 207 views
0
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: { 

}) 

這裏林製作請求與圖像配類型和數據UploadManager。我擔心圖像和數據是互相排斥的,容易出錯。說,我通過.image而不是.video,而向下廣播它會導致崩潰。任何方式來處理這個問題

回答

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!") 
}