Public collections should be immutable

This is, obviously, a very convoluted example. But the thing is that when we do not enforce immutability, bad things may happen, either by distraction, by means of unexpected side effects, or just by means of malicious or misbehaving code.

One way, and it is not the only possible way, to enforce immutability in the precious example might be this:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

finalclassHumanResources{

privatevarinternalEmployeesList:[Person]=[]

varemployees:[Person]{

get{

returnself.internalEmployeesList.map{$0}

}

}

init(){

}

func validateId(id:String)-&gt;Bool{

returnid.characters.count&gt;3

}

func hire(person:Person)throws{

guard validateId(person.id)else{

throwHRError.NotValidID

}

internalEmployeesList.append(person)

}

func fire(person:Person){

iflet index=employees.indexOf({$0.id==person.id}){

internalEmployeesList.removeAtIndex(index)

}

}

}

Notice how we made the mutable collection private, and we provide a readonly property (employees) that returns an immutable collection, built upon request. But, remember, what matters here is not how we create that immutable collection, but the fact that the public API of the HR class provides only immutable data.

No, in normal projects it is not mutable.
You’re likely testing your code in a single Playgrounds file which leads to the behavior you observe. In real projects you usually have HumanResources defined in a different file than from where the class is actually used. In that case “private” modifiers would work then.