swift的异常处理:本质是错误信息的传递方式

    func response(from resultObject: Any) throws -> Response {

        guard

            let dict = resultObject as? [String: AnyObject],

            let transaction = PendingTransaction.from(dict)

        else {

            throw CastError(actualValue: resultObject, expectedType: Response.self)

        }

        return transaction

    }

   

 

 func convertPrivateKeyToKeystoreFile(privateKey: String, passphrase: String) -> Result<[String: Any], KeystoreError> {

        guard let data = Data(hexString: privateKey) else {

            return .failure(KeystoreError.failedToImportPrivateKey)

        }

        do {

            let key = try KeystoreKey(password: passphrase, key: data)

            let data = try JSONEncoder().encode(key)

            let dict = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]

            return .success(dict)

        } catch {

            return .failure(KeystoreError.failedToImportPrivateKey)

        }

    }

 

 

    var asDictionary: [String: Any]? {

        if let data = self.data(using: .utf8) {

            do {

                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]

            } catch {

                print(error.localizedDescription)

                return [:]

            }

        }

        return [:]

    }

posted @ 2019-02-25 11:43  zzfx  阅读(305)  评论(0编辑  收藏  举报