Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are let definitions in a Swift class allocated only once, or per instance?

Tags:

swift

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 multiple instances of Burrito in an application, is the Set meats defined in memory once, separate from the memory allocated for each instance? I would assume that the compiler would optimize that way, but I haven't been able to find an answer on this yet.

EDIT

With the great help from the accepted answer, and the comments about the logic in the isVegetarian() method, here is the modified class. Thanks everybody!

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
    }
}
like image 341
Hayden McCabe Avatar asked Jun 16 '16 16:06

Hayden McCabe


1 Answers

meats is an instance variable of the class. A new instance of meats will be made for every new instance (object) made from the class.

You can use the static keyword to make it a static variable, which will make it so there is only one instance of the meats variable, which is shared among all members of the class.

Immutable instance variables are typically used to be object-wide constants (rather than class-wide, like immutable static variables), which can have independent definitions for each object. In this case, the definition is static, so a smart compiler could optimize it into a static variable. Regardless, you should explicitly mark this static to communicate to users the intent of this variable.

like image 145
Alexander Avatar answered Oct 21 '22 20:10

Alexander