Swift generic class initializer -


i found problem designing result class in swift

struct result<t>{     private let data: t?     let error: nserror?     var issuccess: bool {         {             return data != nil         }     }      init(data: t) {         self.data = data         self.error = nil     }      init(error: nserror) {         self.data = nil         self.error = error     } } 

usage should this

result(data: "something") // t string 

the problem occurs when want pass error

result(error: errorfromsomewhere) //t not specified 

below real application usage:

class parseregistrationprovider: registrationprovider {     func register(model: registrationform) -> promise<result<string>> {         return promise { accept, reject in             let user = pfuser()             user.username = model.nickname             user.password = model.password             user.email = model.emailadreess             user.signupinbackgroundwithblock({ (issuccess, error) -> void in                 if issuccess {                     accept(result(data: "ok"))                 } else {                     var errorresult = result(error: error!) //causes error                     reject(errorresult)                 }             })         }     } } 

"errorresult" causes compiler error:

generic parameter t not inferred

update: approch works correctly:

result<string>(error: errorfromsomewhere) 

i'd suggest use variant type result cause more compact , can used in pattern matching naturally:

enum result<t>{     case data(t?)     case error(nserror)     var issuccess: bool{         get{             switch self{             case .data(_?):                 return true             default:                 return false             }           }     } } 

your code may become this:

class parseregistrationprovider: registrationprovider {     func register(model: registrationform) -> promise<result<string>> {         return promise { accept, reject in             let user = pfuser()             user.username = model.nickname             user.password = model.password             user.email = model.emailadreess             user.signupinbackgroundwithblock({ (issuccess, error) -> void in                 if issuccess {                     accept(result<string>.data("ok"))                 } else {                     var errorresult = result<string>(error: error!) //causes error                     reject(errorresult)                 }             })         }     } 

}


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

css - Can I use the :after pseudo-element on an input field? -