微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否只在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
        }
    }
}

如果我在应用程序中创建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变量的实例,它在类的所有成员之间共享.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐