Answers for "throwable methods swift"

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
0

swift do catch

do {
    let sandwich = try makeMeSandwich(kitchen)
} catch let error {
    print(error.localizedDescription)
}
Posted by: Guest on December-07-2020

Code answers related to "Swift"

Browse Popular Code Answers by Language