Diciamo che ho la seguente classe Swift semplice:Le definizioni di una classe Swift sono assegnate solo una volta o per istanza?
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
}
}
}
Se creo più istanze di Burrito in un'applicazione, è l'insieme carni definite in memoria una volta, separati dalla memoria allocata per ogni istanza? Suppongo che il compilatore ottimizzerebbe in questo modo, ma non sono ancora riuscito a trovare una risposta.
EDIT
Con il grande aiuto dalla risposta accettata, e le osservazioni circa la logica nel metodo isVegetarian(), qui è la classe modificata. Grazie a tutti!
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
}
}
Nota a margine: 'fillings.intersect (carni) .count> 0' è un'espressione che restituisce un' Bool'. Non è necessario avvolgerlo in un 'if' /' else' e manualmente 'return'' true'/'false'. Si può semplicemente usare: 'return! (Fillings.intersect (meat) .count> 0)' – Alexander
Nice catch. L'ho buttato velocemente insieme per provare alcune cose con i test unitari e non pensavo chiaramente. –
@AMomchilov O semplicemente 'return fillings.intersect (meat) .isEmpty';) – Hamish