String reference guide for Swift

This is the first of many reference guides we are creating to make learning Swift a bit easier, be sure to bookmark it for easy access and keep checking back for new guides. Whether you are a Swift beginner or an expert, our string reference guide is here to help.

If you spot an error or want to add something to this page, leave a comment at the bottom.

Creating a mutable string
Creating an immutable string
Creating a stand-alone character
Initializing an empty string
Concatenating strings and characters
Looping through characters in a string
Counting characters in a string
Adding different types to a string (Interpolation)
Checking for string equality
Check if a string contains another string
Capitalize a string
Making a string uppercase
Making a string lowercase
Retrieving a substring
Trimming the whitespace from a string
Split string into an array
Split string using more than one character
Replace characters in a String
Convert a String to NSData
Convert a String to Int


Creating a mutable string
Notice that the beginning of the line begins with var, which means variable and allows this text to be changed in the future if needed.

var string = "Here is my string that can be changed"


Creating a immutable string
Notice that the beginning of the line begins with let, which means constant and therefore you will only use this when the value will never change.

let myString = "Here is my string that can't be changed"


Creating a stand-alone character
Creates a character constant

let euroSymbol: Character = "€"

 

Creates a character variable

var sessionSymbol: Character = "€"

 


Initializing an empty string

var emptyString = ""

//or

var emptyString = String()


Concatenating strings and characters
This example shows how to join a string with the + operator.

var firstString = "Hello my name is "

var secondString = "Bob"

var finalString = (firstString + secondString)
//Result is "Hello my name is Bob"

This example shows how to join a character with a string:

var myString = "The Euro symbol is "
var myCharacter: Character = "€"

myString.append(myCharacter)
//Result is "The Euro symbol is €"

 

  • Note 1: You must use the append method when working with characters (no longer the +- operator).
  • Note 2: While you can join a character to a string, it doesn’t work the other way around.


Looping through characters in a string
Loop through an string variable

var myString = "This is a string"

for character in myString.characters{
   print(character)
}

 

Loop through a string

for character in "This is a string".characters{
   print(character)
}

//These code snippets will output each character of the string into the console.


Counting characters in a string
To check how many characters are in a string, we use the count function on the characters.

var myString = "Here is my string, lets count the characters!"

print(myString.characters.count)
//Returns 45

 

 


String Interpolation (Adding different types to a string) 
Basic Example:

let numberOfChickens = 3
var myString = "John has \(numberOfChickens) chickens."

//Result is "John has 3 chickens."

 

You can also do calculations inside a string:

var myString = "Later this year, John will have \((numberOfChickens) * 3) chickens."

//Result is "Later this year, John will have 9 chickens."

 
 


Checking for string equality

var myString = "Bob"
var myOtherString = "Bob"
        
if(myString == myOtherString){
            
   //Strings are the same
        
}


Check if a string contains another string

var myString = "Swift is really easy!"

if myString.rangeOfString("easy") != nil {
    
    print("Exists!")
    
}


Capitalize a string new
To capitalize all words in a string use the .capitalizedString method.

var myString = "berlin is poor but sexy."
myString.capitalizedString
//myString is now "Berlin Is Poor But Sexy"

To capitalize only the first word in a String, we use replaceRange in combination with the .capitalizedString method.

var myString = "berlin is poor but sexy."
myString.replaceRange(myString.startIndex...myString.startIndex, with: String(myString[myString.startIndex]).capitalizedString)
//myString is now "Berlin is poor but sexy"


Making a string uppercase
To convert to uppercase use the .uppercaseString method.

let myString = "Wait a moment, please."
let newString = myString.uppercaseString
//The string is now "WAIT A MOMENT, PLEASE."


Making a string lowercase
To convert to lowercase use the .lowercaseString method.

let myString = "Wait a moment, please."
let newString = myString.lowercaseString
// The string is now "wait a moment, please."


Retrieving a substring
Skip x amount of characters from the beginning.

let str = "Hello, darling."
var index1 = str.startIndex.advancedBy(5)
var substring1 = str.substringFromIndex(index1)

//This jumps over the first 5 characters of the string and grabs the rest,
//which returns "darling"

 

Get x amount of characters from the start of the string.

let str = "Hello, darling."
var index1 = str.startIndex.advancedBy(5)
var substring1 = str.substringToIndex(index1)

//This grabs the first 5 characters of the string and stops there,
//which returns "Hello"


Trimming the whitespace from a string
If you need to trim the extra spaces off the beginning and end of your string, use stringByTrimmingCharactersInSet.

var myString = "    Let's trim the whitespace    "
var newString = myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
//Returns "Let's trim the whitespace"

 

You can also easily remove whitespace and new line characters at the same time using this character set:

var newString = myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())


Split string into an array
We can easily extract substrings by using componentsSeparatedByString and specifying the character(s) that is separating them.  In this example, city names are separated by a comma.

var myString = "Berlin, Paris, New York, San Francisco"
var myArray = myString.componentsSeparatedByString(",")
//Returns an array with the following values:  ["Berlin", " Paris", " New York", " San Francisco"]

 

Alternate Example:
Notice in this example that myArray specifically creates an array that can only hold strings.

var myString = "Here is my string"
var myArray : [String] = myString.componentsSeparatedByString(" ")
//Returns a string array with the following values:  ["Here", "is", "my", "string"]

 


Split string using more than one character
If you need to separate your substrings with more than one character, use componentsSeparatedByCharactersInSet. In this example, we want to extract strings that are separated by a hyphen or a space.

var myString = "One-Two-Three-1 2 3"
var array : [String] = myString.componentsSeparatedByCharactersInSet(NSCharacterSet (charactersInString: "- "))
//Returns ["One", "Two", "Three", "1", "2", "3"]



Replace characters in a String
In this example, we are searching a string for whitespace and replacing each instance with a dash “-“.

let myString = "Here is the string"
let replacedString = String(myString.characters.map {
    $0 == " " ? "-" : $0
    })

print(replacedString) //Outputs "Here-is-the-string" to the console.



Convert a String to NSData
To convert a string to NSData, we use dataUsingEncoding().

let myString = "String to encode"
let data = myString.dataUsingEncoding(NSUTF8StringEncoding)


Convert a String to Int new
To convert a string to an int in Swift, we use the .toInt() method. For more information on integers, see our Integers reference guide.

let currentAge = "30" //Our string value
let ageInteger = (Int(currentAge))
print(ageInteger!) //Unwrap the returned optional by adding an exclamation point.

 

That’s it for now, be sure to bookmark this page as we update it regularly. If you found this page useful please consider sharing it with your networks or leave a comment below.