ios - How do I avoid type lost? -


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)! nsdata     let options = ["resourcetype": "image"]     //api call   }    static func uploadvideo(filepath: nsurl, completion: response -> void ) {     let options = ["resourcetype": "video"]     //api call    } } 

sample call be:

uploadmanager.upload(.image, data: data, completion: {  }) 

here im making request uploadmanager .image type , data. concern image , data mutual exclusive , prone error. say, passed .image instead of .video , while downcasting lead crash. way handle problem

you can embed data in enum. example:

enum media {   case image(image: uiimage)   case video(url: nsurl) } 

and can extract them in 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)     } } 

then, can call method this:

let image = uiimage() uploadmanager.upload(.image(image)) { response in     print("upload complete!") } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -