Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/a5d703f3fae68ab3fd5e to your computer and use it in GitHub Desktop.
Save xeoncross/a5d703f3fae68ab3fd5e to your computer and use it in GitHub Desktop.
Objective-c is basically typing for the fun of it.
// JS
var one = "Hello",
var two = "World";
var three = one + " " + two;
// Go
one, two := "Hello", "World"
three := one + " " + two
// PHP
$one = "Hello";
$two = "World";
$three = $one . " " . $two;
// Swift
let one = "Hello"
let two = "World"
let three = one + " " + two;
// Objective-C
NSString *one = @"Hello";
NSString *two = @"World";
NSString *three = [[one stringByAppendingString:" "] tringByAppendingString:two]
@pilotmoon
Copy link

Poor example. There's no need for stringWithFormat here. Just do:

NSLog("%@ %@", one, two);

Also you can write:

NSString *one = @"Hello", *two = @"World";

@tomsterritt
Copy link

Even if just concatenating
[one stringByAppendingString:two]

@xeoncross
Copy link
Author

Thanks @tomsterritt, that did help shorten the code.

@invariant, my mistake using NSLog/Println in the examples. The point was to concatenate strings, not find a quick way to print them.

@harlanhaskins
Copy link

All of these issues are because of backwards compatibility with C, though.

You have to have @'s in front of all the literal a because, in C, "" is a char*, {} denotes scope, structs, or arrays, etc.

And they can't override + to concatenate strings, because that breaks C compatibility. +, with two pointers, adds their addresses.

@silverbelt
Copy link

You concatenation with a space can be done with:
NSString *three = [NSString stringWithFormat:@"%@ %@", one, two];

@danieljfarrell
Copy link

This is because of Objective-C's Smalltalk routes. It's verbose because the syntax was designed for message passing. Text processing is very verbose in Objective-C. Apple did a great job of modernising the language to 2.0 which cuts down a little on the boilerplate. Swift takes things further.

@tewha
Copy link

tewha commented Aug 21, 2014

This will work:

NSString *three = @"Hello" @" " @"World";

All but the first @ are optional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment