Swift 2试试catch而不是let let

时间:2015-09-25 12:16:33

标签: swift2

我正在努力将我的逻辑转换为Swift 2,从1.2中的正常工作转变为希望有人可以启发我吗?

这是Swift 1.2,它允许我更新记录或插入新记录......

 if let people: [People] = DataManager.getContext().executeFetchRequest(fetchRequest) as? [People] {

      // stuff here

        DataManager.saveManagedContext()
    }
    else if let person: People = NSEntityDescription.insertNewObjectForEntityForName(entityNamePeople, inManagedObjectContext: DataManager.getContext()) as? People {

       // stuff here

        DataManager.saveManagedContext()
    }

但现在在Swift 2中我有这个,我认为与1.2代码中的第一个if语句相同并且允许更新记录,但是如果/ else,我如何操作插入部分?

 do {

        let people:[People] = try DataManager.getContext().executeFetchRequest(fetchRequest) as! [People]

        // stuff here

        DataManager.saveManagedContext()

    } catch {

    }

2 个答案:

答案 0 :(得分:1)

您仍可以if let使用try

do {

    if let people = try DataManager.getContext().executeFetchRequest(fetchRequest) as? [People] {
        // stuff here
    } else if let person = try NSEntityDescription.insertNewObjectForEntityForName(entityNamePeople, inManagedObjectContext: DataManager.getContext()) as? People {
        // stuff here
    }

    DataManager.saveManagedContext()

} catch {
    print(error)
}

注意:我没有验证你的函数是否实际抛出,我只是回答了if else问题,所以我在我的例子中使用了try但是你必须检查它是否正确。

答案 1 :(得分:-1)

检查此代码,使用guard / throws可以帮助您更好地

    guard let people: [People] = DataManager.getContext().executeFetchRequest(fetchRequest) as? [People] else { throw MessageType.description }

        // stuff here

    DataManager.saveManagedContext()

   guard if let person: People = NSEntityDescription.insertNewObjectForEntityForName(entityNamePeople, inManagedObjectContext: DataManager.getContext()) as? People { throw throw MessageType.description }

       // stuff here

    DataManager.saveManagedContext()