Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

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?

share|improve this question
    
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 12 hours ago
    
Thanks for that! That helps me using the right words. Do you know what the parentheses are for? –  S. Eberl 12 hours ago
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 12 hours ago
    
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 –  S. Eberl 12 hours ago
    
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. :-) –  S. Eberl 12 hours ago

1 Answer 1

up vote 3 down vote accepted

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

share|improve this answer
    
So: var emptyArray = [String](); instantiates an object of the type emptyArray and emptyArray is a array of strings? –  S. Eberl 11 hours ago
    
@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. 11 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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