Answers for "swift function signature for response and exception"

1

swift create a method who can return result or throw an error

class SecurityService {
  static func loginWith(email: String, password: String, callback: (error: NSError?, user: User?) -> Void) -> Void {

    let URL = ".."
    let params = [
      "email": email,
      "password": password
    ]

    HTTP.request(URL, method: "POST", params: params) { (error, result) in
      if let error = error {
        callback(error: error, user: nil)
      } else {
        guard let JSON = result else {
          let someDomain = "some_domain"
          let someCode = 100
          let someInfo = [NSLocalizedDescriptionKey: "No results were sent by the server."]

          let error = NSError(domain: someDomain, code: someCode, userInfo: someInfo)
          callback(error: error, user: nil)
          return
        }

        guard let name = JSON["name"] as? String, email = JSON["email"] as? String else {
          let someDomain = "some_domain"
          let someCode = 100
          let someInfo = [NSLocalizedDescriptionKey: "No user properties were sent by the server."]

          let error = NSError(domain: someDomain, code: someCode, userInfo: someInfo)
          callback(error: error, user: nil)
          return
        }

        let user = User(name: name, email: email)
        callback(error: nil, user: user)
      }
    }
  }
}
Posted by: Guest on June-09-2020

Code answers related to "swift function signature for response and exception"

Code answers related to "Swift"

Browse Popular Code Answers by Language