📜  swift 创建一个可以返回结果或抛出错误的方法 - Swift 代码示例

📅  最后修改于: 2022-03-11 15:00:57.704000             🧑  作者: Mango

代码示例1
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)
      }
    }
  }
}