Tag Archives: Prefer Literal Syntax over the Equivalent Methods

Item 3, Prefer Literal Syntax over the Equivalent Methods

Note: This post is part 3 of a series of posts I will do about the new book of Matt Galloway.

Prefer Literal Syntax over the Equivalent Methods

Literals have been around objective-c since a long time:

NSString *aString = @"Hello World";

With the latest versions of Clang, this sugar syntax has been extended to NSNumbers, NSArrays & NSDictionaries. Since we deal with this kind of objects every day, this new feature is well appreciated. In a nutshell this allow us to:

  • Reduce the boilerplate
  • Cleaner code
  • Faster typing

While using NSNumbers, you can use literals in the following way:

  • @15 => [NSNumber numberWithInt:15]
  • @15.6 =>[NSNumber numberWithFloat:15.6]
  • @15.123123 => [NSNumber numberWithDouble:15.123123]
  • @YES => [NSNumber numberWithBool:YES]

As you can see, in this case, the amount of extra code is reduced in more than 75%.

You can also use literals in collections with subscripting. With NSArray you can do the following:

  • @[@"One", @"Two"] => [NSArray arrayWithObjects:@"One",@"Two"];
  • By Array subscripting: myArray[1] => [myArray objectAtIndex:1];

And finally with a NSDictionary:

  • @{@"key1":@"object1", @"key2":@"object2"} => [NSDictionary dictionaryWithObjectsAndKeys:@"object1",@"key1",@"object2",@"key2" nil];
  • myDictionary[@"key1"] = @"newObject1"; => [dic setObject:@"newObject1" forKey:@"key1"];

And if you want a mutable object:

  • [@[@"1",@"2" ] mutableCopy];
  • [@{@"key1":@"object1"}mutableCopy];

Although with collections the end result seems the same, if an object is nil, it won’t. While using the common operations adding a nil wouldn’t crash anything, with literals it will:

  • [NSArray arrayWithObjects:@"object1",nil, @"object2", nil] => It’s “ok”.
  • @[@"object1",nil, @"object2"] => It will raise an exception.

In theory it would be better if the first option would crash, because it doesn’t make much sense to have a nil in the middle of an array and work with it in that state. Most of the time, you would prefer that would crash, so you could see immediately where the problem is.

Literals are an awesome addition in a very verbose language like objective-c. Knowing how to use them and their caveats is a must have for every programmer.

Links:

Tagged , , , , , , , , ,