Swift String Operations [Code Snippets]

There are plenty of useful String operations in Swift. However, this article covers what we think every aspiring developer should should know. First off, what are Strings anyway? In simple terms, a String is literally just Text. You can think of it as a bunch of Characters that are “String” together to form Text. Here… View Article
Written by

Chris C

Updated on

Apr 29 2024

Table of contents

    There are plenty of useful String operations in Swift. However, this article covers what we think every aspiring developer should should know.

    First off, what are Strings anyway? In simple terms, a String is literally just Text. You can think of it as a bunch of Characters that are “String” together to form Text.

    Here is an example of a character in Swift:

    var char:Character = "a"
    print(char)
    

    It works the same way as a string but you are only limited to a single character. Thus, using a String is much more useful.

    Initializing a String

    Here is an example for initializing a String:

    var str = ""
    

    Notice that I didn’t need to explicitly declare the variable as a String. This is because Swift sets String as a default initializer for an empty Text. You can usually only encounter Character if it is stated explicitly.

    Multi-line String

    A multi-line String starts and ends with three (3) double-quotation marks (“””). It can also have a pair of quotation marks inside it. To better explain here is a sample:

    let multiString = """
    The Jester put on his hat.  "Where shall I begin,
    please your Majesty?" he asked.
    
    "Begin at the beginning," the King said gravely, "and go on
    till you come to the end; then stop."
    """
    
    print(multiString)
    

    Notice that everything after the first triple double-quotation mark and before the last enclosing triple double-quotation mark will print everything exactly including the line-breaks, quotations, etc. Most of the time these special characters need to be “escaped” before you can print it but multi-line strings will do it for you!

    Special Characters in a String

    Strings can include the following special characters:

    • The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \” (double quotation mark) and \’ (single quotation mark)
    • An arbitrary Unicode scalar value, written as \u{n}, where n is a 1–8 digit hexadecimal number

    Here are examples with their corresponding printed value to better explain special characters:

    let wiseWords = "\"Imagination is more important than knowledge\" - Einstein" // "Imagination is more important than knowledge" - Einstein
    let dollarSign = "\u{24}"        // $,  Unicode scalar U+0024
    let blackHeart = "\u{2665}"      // ♥,  Unicode scalar U+2665
    let sparklingHeart = "\u{1F496}" // ????, Unicode scalar U+1F496
    let cool = "\u{1F60E}" // ????, Unicode scalar U+1F60E
    

    Use special unicode characters to flair up your text! especially when using emojis (here is a list of unicode emoticons).

    Combining Strings (String Concatenation)

    There are many ways to add together (or concatenate) Strings, the first method would using the addition operator (+) to create a new String value:

    let string1 = "code"
    let string2 = " with chris"
    var welcome = string1 + string2
    print(welcome) //prints "code with chris"
    

    You can also add a String value to an existing String variable with the addition assignment operator (+=):

    var str = "look over" 
    str += "there"
    print(str) //prints "look over there"
    

    You can also append a Character value to a String variable with the built-in String append() method:

    var appendStr = "welcome home"
    appendStr.append(" darling!")
    print(appendStr)//prints "welcome home darling!
    

    Counting String Length in Swift

    Counting Strings has many uses. One of which is when you need the length of the string to do a loop or an operation. Below is the code sample of counting a String length:

    let str1 = "code with chris"
    var countedValue = str1.count
    print(countedValue) //prints 15
    

    Converting/Printing an Int to String in Swift

    There are two ways on Converting or printing an Int. Refer below for the example:

    var myInt = 2019
    var intToString = "\(myInt)"
    print(intToString) //prints 2019
    
    var convertedInt = String(myInt)
    print(convertedInt) //prints 2019
    

    Converting/Printing a String to Int in Swift

    Likewise, there are two ways to convert a String to an Int. Refer below for the example:

    let numStr = "357"
    let convertedStr = Int(numStr)
    print(convertedStr) //prints Optional(357)
    
    let convertedStr2 = (numStr as NSString).integerValue
    print(convertedStr2) //prints 357
    

    The first method however, can make your app crash when the value converted is not an Int. Thus, in order to prevent this you need to add an optional value if ever it decides to crash:

    let numStrWithChar = "357!"
    let OptionalInt = Int(numStrWithChar) ?? 2019
    print(OptionalInt) //prints 2019
    

    Getting part of a String (Substring)

    Getting a Substring is quite tricky in Swift but here is an example of the most common one:

    let greeting = "Hi there! welcome to code with chris! ????"
    let endOfSentence = greeting.firstIndex(of: "!")!
    let firstSentence = greeting[...endOfSentence]
    print(firstSentence)//prints "Hi there!"
    

    And thus concludes our quick tour on Useful String Operations in Swift. Feel free to leave a comment for any clarifications.



    Get started for free

    Join over 2,000+ students actively learning with CodeWithChris