如何在Swift中的函数中将表达式作为参数传递?

时间:2018-11-28 06:13:24

标签: ios swift

我是一名初级iOS开发人员。我想重构我的代码。目前,我想重构我的领域方法。为了在Realm中保存或删除数据,我需要到处使用很多do try catch块,因此我想提供一个服务来处理这个问题。我已经尝试过,但是我不知道这是否正确

import RealmSwift

class RealmService {

    private init() {}
    static let shared = RealmService()

    var realm = try! Realm()

    func save(expression: ()) {

        do {
            try realm.write {

            // I want to pass the expression in this block here

                expression
            }
        } catch {
            post(error)
        }

    }


}

用法:

func saveToRealmDatabase(wishList: WishList, product: Product) {


    RealmService.shared.save(expression: {
        // I want to pass expression in the block in here as argument
        wishList.products.append(product)
    }())



}

我想将表达式wishList.products.append(product)作为RealmService类中函数的参数传递。有没有更好的方法来实现这一目标?

2 个答案:

答案 0 :(得分:6)

您的“表达式”可以由类型() -> Void表示-一种不接受任何参数且不返回任何内容的闭包。

这是应该声明您的方法的方式:

func save(expression: @escaping () -> Void) {

    do {
        try realm.write {
            expression()
        }
    } catch {
        post(error)
    }

}

这是您应该如何使用它:

func saveToRealmDatabase(wishList: WishList, product: Product) {


    RealmService.shared.save(expression: {
        wishList.products.append(product)
    })
}

答案 1 :(得分:1)

从您尝试的方法来看,我可以猜到您想做类似的事情,

RealmService.shared.save(expression: {
        wishList.products.append(product)
        realm.add(wishList.products)
    })

因此,基于对要在该回调中执行加法运算的理解,我宁愿建议以下实现,您无需为每个操作实现回调。而是当您有兴趣了解操作状态时,才可以实现回调。检查以下代码段,

class RealmService {

    private init() {}
    static let shared = RealmService()

    var realm = try! Realm()

    /// Saving a list of object i.e, List<Object>
    func save<O, L: List<O>>(_ list: L, callback: ((Error?) -> Void)? = nil) where O: Object {
        do {
            try realm.write {
                realm.add(list)
                callback?(nil)
            }
        } catch {
            callback?(error)
        }
    }

    /// Saving a single object i.e, `Object`
    func save(_ object: Object, callback: ((Error?) -> Void)? = nil) {
        do {
            try realm.write {
                realm.add(object)
                callback?(nil)
            }
        } catch {
            callback?(error)
        }
    }
}

用法

class Dog: Object {
   @objc dynamic var name = ""
   @objc dynamic var age = 0
}

let tomy = Dog()
tomy.name = "Tomy"

let johny = Dog()
johny.name = "Johny"

let dogs = List<Dog>()
dogs.append(tomy)
dogs.append(johny)

//When you are not interested in save operation status
RealmService.shared.save(dogs)

//When you want to handle error while saving
RealmService.shared.save(dogs) { [weak self] in self?.showAlert($0) } 

func showAlert(_ error: Error?) {
    guard let e = error else { return }
    showAlert(alertTitle: "Error", alertMessage: e.localizedDescription, actionTitle: "Back")
}