Are Swift class definitions allowed only once or per instance?

Let's say I have the following simple Swift class:

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 } } } 

If I create several instances of Burrito in the application, does the meat defined in memory set once separately from the memory allocated for each instance? I would suggest that the compiler would optimize this way, but so far I could not find the answer.

EDIT

With a lot of help from the accepted answer and comments about the logic in the isVegetarian () method, here is a modified class. Thanks everyone!

 class Burrito { enum Ingredients { case beans, cheese, lettuce, beef, chicken, chorizo } private static let meats : Set<Ingredients> = [.beef, .chicken, .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 } } 
+6
source share
1 answer

meats is a class instance variable. A new instance of meats will be created for each new instance (object) made from the class.

You can use the static to make it a static variable, because of which it will only have one instance of the meats variable, which is common to all members of the class.

Optional instance variables are typically used as sector-wide constants (rather than in a class, as immutable static variables), which can have independent definitions for each object. In this case, the definition is static, so the smart compiler can optimize it in a static variable. Regardless, you should explicitly mention this static to inform users of the intentions of this variable.

+3
source

All Articles