簡體   English   中英

使用自定義數組的Swift繼承

[英]Swift Inheritance with custom array

class RecipeBrain: NSObject {
    var name: String
    var pictureUrl: String
    var likes = 0
    var ingredients: [Ingredient]
    var method: [String]

    init(name: String, pictureUrl: String, ingredients: [Ingredient], method: [String]) {
        self.name = name
        self.pictureUrl = pictureUrl
        self.ingredients = ingredients
        self.method = method
    }
}

class Ingredient{
    var name: String
    var quantity: Double
    var unit: String

    init(name: String, quantity: Double, unit: String) {
        self.name = name
        self.quantity = quantity
        self.unit = unit
    }
}

class AddRecipe {
    var recipeBrain = [RecipeBrain]()
    var ingredients = [Ingredient]()
    var ingredient = Ingredient(name: "apple", quantity: 1.0, unit: "Kg")
    ingredients.append(ingredient)
    var recipe1 = RecipeBrain(name: "Recipe1", pictureUrl: "nil", ingrexdients: ingredients, method: ["Method"])
    recipeBrain.append(recipe1)
}

我正在嘗試在Swift中構建一個配方應用程序。 問題是為它創造成分,我需要一個字符串,雙,字符串。

我的想象:一種成分是一系列成分。 並創建一個新的配方,我只是將它添加到recipeBrain

主要問題:當我嘗試將新配方附加到recipeBrain數組時它表示沒有聲明recipe1。

(AddRecipe類的目的只是使用靜態數據進行測試)

我將它更改為recipeBrain.append(recipe1)但我仍然得到錯誤:預期聲明,當我嘗試追加時與成分相同

您正嘗試將配方和成分對象附加到AddRecipe類主體的數組中,但您不能。

如果你在方法的主體中這樣做,一切都會好的,例如在init()方法中:

class AddRecipe {
var recipeBrain = [RecipeBrain]()
var ingredients = [Ingredient]()

init()
{
    var ingredient = Ingredient(name: "apple", quantity: 1.0, unit: "Kg")
    ingredients.append(ingredient)
    var recipe1 = RecipeBrain(name: "Recipe1", pictureUrl: "nil", ingredients: ingredients, method: ["Method"])
    recipeBrain.append(recipe1)
}

您收到錯誤消息,因為您已嘗試在類聲明中編寫代碼。 您只能在類聲明中直接聲明屬性,函數,枚舉和其他類。 代碼,例如ingredients.append(ingredient)需要進入函數內部。

我建議您將此代碼移動到RecipeBrain類的類函數中(或者確實將其放在其他地方,例如視圖控制器,但您還沒有顯示應用程序的結構):

class RecipeBrain: NSObject {
    var name: String
    var pictureUrl: String
    var likes = 0
    var ingredients: [Ingredient]
    var method: [String]

    init(name: String, pictureUrl: String, ingredients: [Ingredient], method: [String]) {
        self.name = name
        self.pictureUrl = pictureUrl
        self.ingredients = ingredients
        self.method = method
    }

    class func addRecipe() -> [RecipeBrain] {
        var recipeBrain = [RecipeBrain]()
        var ingredients = [Ingredient]()
        let ingredient = Ingredient(name: "apple", quantity: 1.0, unit: "Kg")
        ingredients.append(ingredient)
        let recipe1 = RecipeBrain(name: "Recipe1", pictureUrl: "nil", ingredients: ingredients, method: ["Method"])
        recipeBrain.append(recipe1)
        return recipeBrain
    }
}

現在,可以說let recipeBrain = RecipeBrain.addRecipe()recipeBrain將陣列RecipeBrain含有單個RecipeBrain

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM