2016-03-15 69 views
0

我有一個init呼叫存在於我的數據庫或者延遲加載我的種子數據,或加載數據:如何在Swift if語句中捕獲0的返回值?

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

createPages()方法不會被調用,因爲loadPages()是最起碼返回0 Results

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 statement抓,使createPages()叫?

回答

2

選項1:

添加回在loadPages()

if results.count == 0 { return 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:

添加whereif let

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

感謝隊友!這工作完美。 – Trip

0

你可以添加一個where條款:

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