Optional property in class
Your syntax
var?.function()
is known as "optional chaining." It tells the compiler "if the variable (which is an Optional) contains nil, stop. If it is not nil, call the function on that object.
If you define an array arrayList
as type [String]?
that creates an Optional variable arrayList
that can contain an array of Strings, or it could be nil. It will start out as nil and stay that way until you save an array into it.
You never store an array in arrayList
, so it's always nil.
Thus your optional chaining always fails to do anything.
As others said in comments, define your arrayList
variable to contain an empty array:
var arrayList = [String]()
Then it will never be nil, and you will always be able to add items to it without using Optional chaining.