小编Hay*_*abe的帖子

是否只在Swift类中定义一次或每个实例分配?

假设我有以下简单的Swift类:

class Burrito {
    enum Ingredients {
        case beans, cheese, lettuce, beef, chicken, chorizo
    }

    private let meats : Set<Ingredients> = [.beef, .chicken, .chorizo]

    var fillings : Set<Ingredients>

    init (withIngredients: Set<Ingredients>) {
        fillings = withIngredients
    }

    func isVegetarian() -> Bool {
        if fillings.intersect(meats).count > 0  {
            return false
        }
        else {
            return true
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我在应用程序中创建Burrito的多个实例,那么在内存中定义的Set meats是否与为每个实例分配的内存分开?我会假设编译器会以这种方式进行优化,但我还没有找到答案.

编辑

在接受的答案的帮助下,以及关于isVegetarian()方法中逻辑的评论,这里是修改后的类.谢谢大家!

class Burrito {
    enum Ingredients {
        case beans, cheese, lettuce, beef, chicken, chorizo
    }

    private static let meats : Set<Ingredients> …
Run Code Online (Sandbox Code Playgroud)

swift

6
推荐指数
1
解决办法
152
查看次数

标签 统计

swift ×1