Spaces in NSDictionary keys

I seemed to recall that keys in an NSDictionary cannot contain spaces, although this seems to work. The documentation states that keys must conform to the NSCopying protocol, but that hasn’t resolved the matter for me. Perhaps I’m confusing dictionaries with records, which require vertical bars if the key (technically a label) contains a space. Thanks for the help.

My test script:

use framework "Foundation"
use scripting additions

-- this works
set theKeys to current application's NSArray's arrayWithArray:{"key one", "key two"}
set TheObjects to current application's NSArray's arrayWithArray:{"value one", "value two"}
set theDictionary to current application's NSDictionary's dictionaryWithObjects:TheObjects forKeys:theKeys
theDictionary's valueForKey:"key one" --> (NSString) "value one"

-- this doesn't work (I didn't expect it to)
# set theRecord to {key one:"value one", key two:"value two"}
# key one of theRecord --> Expected “:”, etc. but found identifier.

-- this works
set theRecord to {|key one|:"value one", |key two|:"value two"}
|key one| of theRecord --> "value one"

I raised this question on the Gemini AI app and got the following response. This seems to confirm my tests, but I’ll leave this thread up just in case anyone has a contrary (or supporting) opinion.

Yes, keys in an Objective-C dictionary can contain spaces. However, it’s generally not recommended because spaces can be confusing and lead to errors when accessing the key.

Here’s why using spaces in dictionary keys is discouraged:

  • Dot notation: Objective-C allows accessing dictionary values using dot notation (e.g., dictionary.key). If the key has spaces, dot notation won’t work.
  • Readability: Keys with spaces can make code harder to read and understand.

Here are some alternatives to using spaces in dictionary keys:

  • Underscores: Separate words with underscores (e.g., date_of_birth).
  • Camel case: Combine words with a capital letter at the start of each word (e.g., dateOfBirth).

Even if it worked in some cases it’s strongly discouraged.
Dictionaries are often used for key-value coding (KVC) and there the rule is

A key is a string that identifies a specific property. Typically, by convention, the key representing a property is the name of the property itself as it appears in code. Keys must use ASCII encoding, may not contain whitespace, and usually begin with a lowercase letter (though there are exceptions, such as the URL property found in many classes).

1 Like

I can confirm that keys in NSDictionary can contain spaces. I’m using them for years in one particular situation where the keys also appear in the UI and I’m too lazy to add a step of using two separate strings for this.

I also agree that in general it shouldn’t be done for all the reasons listed by @peavine and @StefanK.

1 Like

Stefan and Leo. Thanks for the help–I appreciate it.

1 Like