0

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?

7
  • 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. Commented Sep 4, 2015 at 20:01
  • Thanks for that! That helps me using the right words. Do you know what the parentheses are for? Commented Sep 4, 2015 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.) Commented Sep 4, 2015 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 Commented Sep 4, 2015 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. :-) Commented Sep 4, 2015 at 20:35

1 Answer 1

10

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]()

3
  • So: var emptyArray = [String](); instantiates an object of the type emptyArray and emptyArray is a array of strings? Commented Sep 4, 2015 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. Commented Sep 4, 2015 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() Commented Aug 8, 2016 at 21:34

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.