gpt4 book ai didi

ios - 如何在 Swift if 语句中捕获 0 的返回值?

转载 作者:行者123 更新时间:2023-11-28 12:52:33 25 4
gpt4 key购买 nike

我有一个 init 调用,它要么延迟加载我的种子数据,要么加载我的数据库中存在的数据:

    if let savedPages = loadPages() {
pages += savedPages
} else {
createPages()
}

我的 createPages() 方法没有被调用,因为 loadPages() 至少返回了 0 个结果

func loadPages() -> [NSManagedObject]? {

// Load all those pages!
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Page")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
return results as? [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
return nil
}

如何使我的 else 语句 捕获以便调用 createPages()

最佳答案

选项 1:

loadPages()中添加返回

if results.count == 0 { 返回 nil }

func loadPages() -> [NSManagedObject]? {

// Load all those pages!
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Page")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
///
if results.count == 0 { return nil }
///
return results as? [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
return nil
}

选项 2:

if let之后添加where

if let savedPages = loadPages() where savedPages.count > 0 {
pages += savedPages
} else {
createPages()
}

关于ios - 如何在 Swift if 语句中捕获 0 的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36010540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com