Introduction to Swift: Strings

Strings are an collection of characters encloded by double quotes. In Swift strings are represented by the String type. In this tutorial we will take a look at the most used String-based actions. To follow this tutorial you will need Xcode 6 and start a playground file. Xcode 6 can be downloaded from Apple's developer portal.

Initializing empty Strings

var emptyString = ""
// or
var emptyString = String()

Appending Strings

To append strings together you can use the + operator in Swift.

let firstName = "Alex"
let lastName = "Young"
let fullName = firstName + " " + lastName 

The variable name can be used inside a string using interpolation.

println("Hello \(fullName)")
// Hello Alex Young

Comparing Strings

To compare strings in Swift the == operator can be used, the result will be a Boolean.

let oneString = "Hello"
let anotherString = "Hello"

if (oneString == anotherString) {
  println("Strings are equal")
else {
  println("Strings are not equal")

String Conversion 

Sometimes it is very handy to convert an integer to a string and vice versa.

let myNumber = "1234".toInt()  // String to Int
let myString = String(1)

Changing Case in a String

You can change all characters in a string to lowercase.

let myString = "aAbBcC"
let lowerString = myString.lowercaseString // "aabbcc"
let upperString = myString.upercaseString  // "AABBCC"


Strings in Swift are fully Unicode compliant, so you can use emoji characters inside  string

This finished this part of the introduction serie of Swift programming.