加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:01:27 所属栏目:百科 来源:网络整理
导读:假设我有以下简单的 Swift类: class Burrito { enum Ingredients { case beans,cheese,lettuce,beef,chicken,chorizo } private let meats : SetIngredients = [.beef,.chicken,.chorizo] var fillings : SetIngredients init (withIngredients: SetIngredi
假设我有以下简单的 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
        }
    }
}

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

编辑

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

class Burrito {
    enum Ingredients {
        case beans,chorizo
    }

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

    var fillings : Set<Ingredients>

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

    func isVegetarian() -> Bool {
        return fillings.intersect(Burrito.meats).isEmpty
    }

    // All burritos are delicious
    func isDelicious() -> Bool {
        return true
    }
}

解决方法

肉类是该类的实例变量.将为该类生成的每个新实例(对象)创建一个新的肉类实例.

你可以使用static关键字使它成为一个静态变量,这将使它只有一个meats变量的实例,它在类的所有成员之间共享.

不可变实例变量通常用于对象范围的常量(而不是类范围的,如不可变的静态变量),它们可以为每个对象提供独立的定义.在这种情况下,定义是静态的,因此智能编译器可以将其优化为静态变量.无论如何,您应该明确标记此静态以向用户传达此变量的意图.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读