向列表添加元素时Swift运行时错误?

时间:2016-04-17 23:49:46

标签: arrays swift

我正在通过Apple教程学习Swift,当我尝试将我的膳食添加到 meal 数组中时,Xcode会给我一个运行时错误。我尝试使用'追加',但这样做会给我一个"额外的参数调用"错误。

class MealTableViewController: UITableViewController {
// MARK: Properties
var meals = [Meal]()

override func viewDidLoad() {
    super.viewDidLoad()

    loadSampleMeals()
}
func loadSampleMeals() {

    let photo1 = UIImage(named:"Chocolate")!
    let chocolate = Meal(name: "Great Chocolate", photo: photo1, rating: 4)

    let photo2 = UIImage(named: "Curry")!
    let curry = Meal(name: "Smelly Curry", photo: photo2, rating: 1)

    let photo3 = UIImage(named: "Menudo")!
    let menudo = Meal(name: "Red and ready to go", photo: photo3, rating: 5)

    meals += [chocolate,curry,menudo]
}

2 个答案:

答案 0 :(得分:0)

尝试meal.append()而不是运算符

答案 1 :(得分:0)

正如ConfusedByCode指出的那样,您的图片可能是nil,而您正在尝试隐式展开它们(使用!)。

您有三种方法可以解决这个问题:

解决方案1 ​​

确保项目中存在这些图片。

解决方案2

在添加新的nil之前,请确保您的图片不是Meal

func loadSampleMeals() {
    if let photo1 = UIImage(named:"Chocolate") {
        meals.append(Meal(name: "Great Chocolate", photo: photo1, rating: 4))
    }

    if let photo2 = UIImage(named: "Curry") {
        meals.append(Meal(name: "Smelly Curry", photo: photo2, rating: 1))
    }

    if let photo3 = UIImage(named: "Menudo") {
        meals.append(Meal(name: "Red and ready to go", photo: photo3, rating: 5))
    }
}

解决方案3

photo课程中Meal成为可选属性。

class Meal {
    init(name: String, photo: UIImage?, rating: Int) {
    }
}

然后,您可以保留代码(但删除!)。

func loadSampleMeals() {
    let photo1 = UIImage(named:"Chocolate")
    let chocolate = Meal(name: "Great Chocolate", photo: photo1, rating: 4)

    let photo2 = UIImage(named: "Curry")
    let curry = Meal(name: "Smelly Curry", photo: photo2, rating: 1)

    let photo3 = UIImage(named: "Menudo")
    let menudo = Meal(name: "Red and ready to go", photo: photo3, rating: 5)

    meals += [chocolate,curry,menudo]
}