Swift:让detail view controller知道数组可能存在也可能不存在

Swift: Let detail view controller know that array may or may not exist

所以我正在制作一个食谱日记应用程序来存储食谱。在 detail view controller 中有一个 属性 recipe,有一个 table view 的配料,当你打开 detail view controller 你可以添加配料,它们会出现在一个table viewcore data relationship 是一对多的,所以 recipe entity 有一个 NSOrderedSet 的成分,并且该成分有一个 属性 的配方。

但是在 numberOfRowsInSection 方法中,当我尝试添加 return self.recipe?.ingredients.count 时,它告诉我在末尾放置一个 ! 但是当我这样做时它会抛出一个 error 并告诉我将其删除。

它说

Value of optional type Int not unwrapped

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.recipe?.ingredients.count
}

这个我也试过了,也没用

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if self.recipe?.ingredients.count == 0 {            
        return 0        
    }        
    else {
        return self.recipe!.ingredients.count
    }
}

不确定这是否有效,但请尝试

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let recepies = self.recipe? {
        return recepies.ingredients.count
     }

    return 0
}

这将检查配方数组是否存在,如果存在则将 return 计算成分的数量,否则将 return 0。

您尝试使用

检查可选值是否等于 0
if self.recipe?.ingredients.count == 0

如果值等于 0,这只会 return true。如果值等于 nil,它将 return 为假(如果recipenil.

而是尝试确定您的 recipes 是否 nil

if let recipe = self.recipe {
  //Check if self.recipe is not equal to nil and assign the value to recipe if it is not equal to nil.
  return recipe.ingredients.count
}else{
  /return 0 if recipe is equal to nil
  return 0
}