Strings in Swift

Become a Subscriber

Strings are simply an array of characters. If you come from an Objective-C background, you’ll remember that you had to use the @ sign before quotation marks that wrap the string. This was to tell the compiler that it was an Objective-C string literal. In Swift, the @ sign is not required. Simply use double quotation marks "i am a string" and Swift will implicitly know it is a string.

You can declare the string explicitly by specifying the type String:

var str:String = "Hello, world!"

But Swift will recognize it implicitly as well:

var str = "Hello, world!"

We said a string is an array of characters, and you can actually see this by typing this statement into a playground:

for char in str {
  println(char)
}

Don’t worry about the for statement for now, but you can see the console has outputted the following:

Screenshot

Strings are exceptionally useful. Humans don’t interpret things as 1’s and 0’s, we tend to need more description. Strings let us assign bits of code to things that are human readable.

One last thing: strings are what are known as value types. That means when you pass a string into a function, the value gets copied and when you pass it back, you also get a copy. So if you manipulate a string in any way, you can be sure that you are not manipulating the original string. Those coming from an Objective-C background, this will be a change to be aware of.