2

The following is causing my cpu to die and the program to freeze

var animals = ["B":["Bear", "Black Swan", "Buffalo"], "C": ["Camel", "Cockatoo"], "D": ["Dog", "Donkey"], "E": ["Emu"], "G": ["Giraffe", "Greater Rhea"], "H": ["Hippopotamus", "Horse"], "K": ["Koala"], "L": ["Lion", "Llama"], "M": ["Manatus", "Meerkat"], "P": ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"], "R": ["Rhinoceros"], "S": ["Seagull"], "T": ["Tasmania Devil"], "W": ["Whale", "Whale Shark", "Wombat"]]

Taking off the array definition from key elements associated with a single Animal does work fine, however, I don't know what is going on?

var animals = ["B":["Bear", "Black Swan", "Buffalo"], "C": ["Camel", "Cockatoo"], "D": ["Dog", "Donkey"], "E": "Emu", "G": ["Giraffe", "Greater Rhea"], "H": ["Hippopotamus", "Horse"], "K": "Koala", "L": ["Lion", "Llama"], "M": ["Manatus", "Meerkat"], "P": ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"], "R": "Rhinoceros", "S": "Seagull", "T": ["Tasmania Devil"], "W": ["Whale", "Whale Shark", "Wombat"]]

May be try the above code in playgrounds to see the effect.

Ahmed Ebaid
  • 417
  • 6
  • 21

1 Answers1

2

Tell it what the type is – there are too many possibilities and it’s struggling:

var animals: [String:[String]] = [
    "B": ["Bear", "Black Swan", "Buffalo"], "C": ["Camel", "Cockatoo"], "D": ["Dog", "Donkey"], "E": ["Emu"],"G": ["Giraffe", "Greater Rhea"], 
    "H": ["Hippopotamus", "Horse"], "K": ["Koala"], "L": ["Lion", "Llama"], "M": ["Manatus", "Meerkat"], "P": ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"], 
    "R": ["Rhinoceros"], "S": ["Seagull"], "T": ["Tasmania Devil"], "W": ["Whale", "Whale Shark", "Wombat"]]

The problem being, it could be a [Character:[String]], a [NSString:[NSString]], a [String:[AnyObject]], a [String:NSArray], an NSDictionary, etc. The combinations, they explode, and so does the poor compiler.

This will also help you when you inevitably make a typo and make one of the values a string instead of an array of strings, and Swift decides to AnyObject all the things.

p.s. if you want a Q, there’s always Quail.

Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
  • Thank you AirSpeed, didn't get your p.s.?. Is it a recommendation to always define the type and not being as smart or it is only for my case because It could have a variety of options. – Ahmed Ebaid Apr 17 '15 at 12:09
  • 1
    The p.s. was a joke, I noticed you were missing a Q animal :) My advice is only to specify the type when you need to (resolving ambiguity, either for performance or correct logic being the main time you need to do it). Other than that, type inference is preferred as it reduces clutter. But annoyingly, the NS types are very permissive in their conversion to `AnyObject` so it’s sometimes a good idea with literals – I wish it weren’t, and hoping that will change in future versions of Swift. – Airspeed Velocity Apr 17 '15 at 12:12