-4

I am new to Swift Programming language. I am learning it from Apple's site. I came across below line of code:

let emptyArray = [String]()

I have asked another question related to this but not completely. I want to know that what are the pros and cons of creating an empty immutable array in Swift. As above line of code contains let keyword, it clearly states that an empty array of string type will be created in memory. My point of interest is that why anyone would be needing that? Is there any use for it? otherwise, Apple wouldn't have allowed it. So I want to know the pros and cons of an example.

Note: I have searched in Google and StackOverflow for my query but did not found the exact reason what I am looking for. So please think before you downvote this question.

Edit: Previously asked question does not address my current question at all. By this question, I want to know that in what scenario(s) I should do it. Why Apple does provide such feature which allows us to create an empty immutable array. Because an empty array there would be no value and after creating it you wouldn't be able to edit its value as its empty and neither you would be able to add or remove any item into/from it. So why compile allows to write such line? Hope I am clear now.

Innat
  • 16,113
  • 6
  • 53
  • 101
Priyank Sheth
  • 2,352
  • 19
  • 32
  • 2
    Imagine a function that creates a "Person" object and takes an array of phone numbers as parameter. Why should passing an empty array be disallowed? – Martin R Jun 02 '15 at 12:42
  • Or thinking functional, when you avoiding the mutable state, imagine an "append" function, that does not modify the original array, but creates a new one from the original array + the appended value. – Dániel Nagy Jun 02 '15 at 13:37

1 Answers1

1

My point of interest is that why anyone would be needing that?

Perhaps no one does need it. Just because it is possible to do in Swift doesn't imply that anyone uses it or finds it useful.

Is there any use of it?

I suppose we could come up with contrived examples, but if you need it then use it. If you find it useless, fine, don't use it.

otherwise Apple wouldn't had allowed it

I think you're reading more into this than there is. Apple doesn't consider every possible line of code than can be written in Swift and then allow or disallow it. The fact that you can do this is a natural extension of the fact that you can initialize a variable when you create it. If you declare it with var then it is mutable, and if you declare it with let it is immutable. On what grounds would Apple disallow the creation of an immutable empty array? Because they can't think of a use for it? That would really frustrate a programmer who did come up with a use for it.

vacawama
  • 150,663
  • 30
  • 266
  • 294