0
var persons = [Dictionary<String, String>()]
println(persons.count)

prints 1. I see that there is an empty dictionary inside the array when it is initialized but is there a way to avoid that and having 0 elements instead of 1? Later I need to be able to do:

persons.append(["firstName": "Foo", "lastName": "Bar"])

Any ideas?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601
  • Wasn't that answered in http://stackoverflow.com/a/26735091/1187415 in reply to your previous question? Did you copy the suggested code correctly? – Martin R Nov 04 '14 at 13:27
  • @MartinR your right, but as I wrote this question I thought it is a different problem. We may close this. – DarkLeafyGreen Nov 04 '14 at 13:33
  • I feel guilty... it's me who answered to the other question, and I should have noticed that, considering that the answer is pretty much the same. @MartinR, do you think I should delete my answer here? – Antonio Nov 04 '14 at 14:16
  • @Antonio no totally fine, you don't have to delete it. – DarkLeafyGreen Nov 04 '14 at 14:28
  • @Antonio: You can't delete the answer anymore because it has been accepted. – Martin R Nov 04 '14 at 14:32

3 Answers3

5

By using this:

[Dictionary<String, String>()]

you are creating an array with one element Dictionary<String, String>()

The correct way is to move the parenthesis after the square brackets:

[Dictionary<String, String>]()

That declares an array of type Dictionary<String, String>, and instantiate it.

Equivalent way of creating it is:

Array<Dictionary<String, String>>()
Antonio
  • 71,651
  • 11
  • 148
  • 165
1

Just place brackets outside:

var persons = [Dictionary<String, String>]()
nicael
  • 18,550
  • 13
  • 57
  • 90
-1

Shouldn't it be

var persons = Dictionary<String, String>()
println(persons.count)

or

var persons = [String : String]()
println(persons.count)

but not both syntaxes at the same time?

https://developer.apple.com/library/mac/documentation/General/Reference/SwiftStandardLibraryReference/Dictionary.html

arieljuod
  • 15,460
  • 2
  • 25
  • 36