Continuing with strings, Swift offers some additional conveniences versus other languages, making it easier for the beginner to grasp the language.
Often, it's necessary to build a string from a set of smaller strings. This process is known as concatenation. Concatenation in C requires the use of a special function, sprintf, which does the work. Consider the breakdown of the sentence “The dog chased the cat” into subject-verb-object, and assembling those components in a sentence in C:
char *subject = “The dog"; char *verb = “chased"; char *object = “the cat"; char sentence; sprintf(sentence, “%s %s %s.", subject, verb, object);
This code works, but it seems rather obtuse for such a simple operation. The sprint() function requires a buffer of bytes to hold the sentence—this minor detail can lead to problems if the buffer isn't large enough, adding risk for the user. There are ways to mitigate that risk by using functions such as snprintf(), but the buffer allocation step is still needed.
Let's see how Objective-C handles the same sentence:
NSString *subject = @"The dog"; NSString *verb = @"chased"; NSString *object = @"the cat"; NSString *sentence = [NSString stringWithFormat:@"%@ %@ %@.", subject, verb, object];
This design is certainly an improvement—goodbye to the detail of worrying about a buffer large enough to hold the sentence. Yet, just as with C, you're dealing with formatting codes and ordering of variables relative to them.
In Swift, the code to handle this simple sentence is much more natural, as shown on lines 13-17 in Figure 3.
Figure 3 Constructing a sentence using strings in Swift.
The let keyword declares a constant whose value will not change throughout the program. In the case of the subject and verb, the declaration has the String type. The exception is line 15, where we take advantage of Swift's aforementioned type-inference feature: The assignment of the constant to a string is enough for Swift to know the type.
On line 17, the concatenation is easy and natural using the plus (+) operator—the same operator used to add two numbers. The Results area on the right provides visual confirmation that the concatenation was ordered successfully.