The following:

var emptyArray = [String]();

What do I need the parentheses () for? [String] says, that the array accepts strings only. But why do I have to put the () there?

  • Just a quick terminology note: "Brackets" are the rectangular things you put around the word String. The round things afterward are parentheses, or just "parens" if you're being informal. – Mason Wheeler Sep 4 '15 at 20:01
  • Thanks for that! That helps me using the right words. Do you know what the parentheses are for? – PeterPan Sep 4 '15 at 20:14
  • 2
    I'm not a Swift developer, but if I had to guess, I'd say it's probably "constructor notation": the [String] denotes a type: array of strings, but you're not trying to assign a type to emptyArray; you're trying to assign an instance of that type, which is where the parens come in. (Note: if any actual Swift devs see this and I'm way off, bear in mind the above: I've never used Swift. Just making an educated guess here.) – Mason Wheeler Sep 4 '15 at 20:20
  • I have actually no idea what you're talking about! You might be right but I don't understand some things like "constructor notation". I can't imagine what that is about. But that's probably because I'm German and English is not my mother tongue. So if you or someone else has another 'easier' explanation, give it to me! :-D – PeterPan Sep 4 '15 at 20:28
  • I reread it a few times and now I guess I understand what you were trying to say. If any swift developer could say whether that's true or not, that'd be great. :-) – PeterPan Sep 4 '15 at 20:35

Two things are true in Swift:

  1. To instantiate an object of type T in Swift you write code T().
  2. The type "name" of an array of Strings is [String]

Combine the two and you get [String]()

  • So: var emptyArray = [String](); instantiates an object of the type emptyArray and emptyArray is a array of strings? – PeterPan Sep 4 '15 at 20:47
  • 3
    @S.Eberl No, the type is "array of String". I've never written Swift, but I doubt it has a type "empty array". So you're creating an object of type "array of String" which happens to be empty. The emptiness itself isn't part of the type. – Andres F. Sep 4 '15 at 21:20
  • 1
    Number 1 doesn't explain why that is, and number 2 doesn't elaborate much. Let me fill the holes: T() is a shorthand for T.init(). [String] is a shorthand for Array<String>. Thus, [String]() is a shorthand for Array<String>.init() – Alexander - Reinstate Monica Aug 8 '16 at 21:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.