Wednesday, June 10, 2015

Basic String Manipulation

In Swift, strings are represented by the String type, which is fully Unicode-compliant. You can declare strings as variables or constants:

let dontModifyMe = "You cannot modify this string"
var modifyMe = "You can modify this string"

In Objective-C, you have to choose between NSString and NSMutableString classes to indicate whether the string can be modified. You do not need to make such choice in Swift. Whenever you assign a string as variable (i.e. var), the string can be modified in your code.

Swift simplifies string manipulating and allows you to create a new string from a mix of constants, variables, literals, as well as, expressions. Concatenating strings is super easy. Simply add two strings together using the “+” operator:

let firstMessage = "Swift is awesome. "
let secondMessage= "What do you think?"
var message = firstMessage + secondMessage
println(message)

Swift automatically combines both messages and you should see the following message in console. Note that println is a global function in Swift to print the message in console.
Swift is awesome. What do you think?
You can do that in Objective C by using stringWithFormat: method. But isn’t the Swift version more readable?

NSString *firstMessage = @"Swift is awesome. ";
NSString *secondMessage = @"What do you think?";
NSString *message = [NSString stringWithFormat:@"%@%@", firstMessage, secondMessage];
NSLog(@"%@", message);

String comparison is more straightforward. In Objective C, you can’t use the == operator to compare two strings. Instead you use the isEqualToString: method of NSString to check if both strings are equal. Finally, Swift allows you to compare strings directly by using the == operator.

var string1 = "Hello"
var string2 = "Hello"
if string1 == string2 {
        println("Both are the same")
}

No comments:

Post a Comment