Coding Explorer Blog

Exploring how to code for iOS in Swift and Objective-C

  • Home
  • Apps
  • About
  • Contact

Swift Strings

Xcode 11.6 Swift 5.2.4

Last updated on August 10, 2020

Strings are a very common type of variable in many programming languages.  Strings are sequences of characters, used to store text.  Swift in particular works with them in a Unicode-compliant way.  In this post we will discuss some of the higher level aspects of working with Strings in Swift.  The Swift String is very different from its predecessor NSString, but they are bridged together in such a way that you can use a Swift string anywhere you would use an NSString.  You can also use NSString methods on Swift Strings.  In Swift 1.2, NSStrings are not automatically bridged to Swift Strings (but they were beforehand), they must be typecast using the “as” operator.  Swift Strings can still be used where an NSString is expected though, so you only have to typecast an NSString to its Swift equivalent if you still have one.

String Literals

Firstly, I never really learned what “literal” in this context meant directly.  I eventually figured it out from context, but I felt I should just say it outright for others like me that keep hearing it, but don’t actually get told the definition.  I feel Wikipedia’s introductory line about Literals does it justice:  “In computer science, a literal is a notation for representing a fixed value in source code.”

In Swift, as in most languages, a String literal is just text written between two quotation marks.  You can bind it to a variable or constant, as well as use it directly as a parameter to a function.

There are also a few special characters that can be used in String literals to describe special things like tabs or new lines.  These include:

  • \0 – Null character (that is a zero after the slash)
  • \\ – Backslash itself.  Since the backslash is used to escape other characters, it needs a special escape to actually print itself.
  • \t  – Horizontal tab
  • \n – Line Feed
  • \r  – Carriage Return
  • \”  – Double quote.  Since the quotes denote a String literal, this is necessary if you actually want to print one.
  • \’  – Single Quote.  Similar reason to above.

Sadly, it appears vertical tab did not make the cut.

String Initializers

Besides using string literals, Swift provides another way to create strings, initializers.  They are overloads of the String init method that take different arguments and create a Swift String version of that variable.

Empty Strings

Swift gives two easy ways to create an empty string.  The first is to just use an empty string literal, the second is to initialize a string with no parameters, like so:

let someString = String()

Since there are no parameters, the initializer has no choice but to return an empty string, ready and waiting to have additional information concatenated to it.

Swift Strings are Structures

Strings in Swift are not implemented via a class, they are actually structures.  That means they are value types.  That in turn means that when you assign them to a new variable, they are copied, so when you change the original String that was copied, the newly stored one is unaffected.  This is in contrast to NSString in Objective-C, which was a class, and would be passed by reference.  If you changed one reference to that initial NSString, you changed them both.

Working with Strings

Strings have a few operators that make working with them easier.

String Concatenation

Like in other languages, Strings can be concatenated (put together) with a plus sign ” + ” operator.  It just basically has the compiler create a string with the characters of the second string placed at the end of the first string.  For example:

let firstString = "I like "
let secondString = "Swift!"

let wholeSentence = firstString + secondString
print(wholeSentence)

That will print the sentence “I like Swift!” to the console.

String Comparison

As one would expect, you can compare if two strings are the same like you would in any other equality test, with ” == ” and ” != “.  These will return a Bool describing whether they are equal or not.  Since Swift Strings are Unicode based, and I know very little about Unicode, I will let Apple’s iBook define String equality for me:

“Two String values (or two Character values) are considered equal if their extended grapheme clusters are canonically equivalent. Extended grapheme clusters are canonically equivalent if they have the same linguistic meaning and appearance, even if they are composed from different Unicode scalars behind the scenes.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

If you wanted to store whether two strings were equal to each other to a variable, you would do it like so:

let firstSentence  = "This is a sentence."
let secondSentence = "This is a sentence."

let areTheyEqual = (firstSentence == secondSentence)

The variable “areTheyEqual” would then have a value of “true”.

String Interpolation

You have seen me use this before, but it should be stated here.  String interpolation lets you easily put values into Strings, so you could have something like this:

let length = 7
let width = 3

print("The rectangle has a length of \(length) and a width of \(width), giving it an area of \(length * width).")
//Outputs:  The rectangle has a length of 7 and a width of 3, giving it an area of 21.

This works with many built in types, and as you saw here, even with expressions (the multiplication of the two variables, in this case).

Conclusion

Strings are a very important part of many programs, and Apple did a great job implementing Swift’s version of the String type.  While learning about Strings, we even got an introduction to initializers and the wildcard pattern, which are both other important aspects of Swift.  We will cover these more at a later date.  If you want to learn more about those, check my future posts Class Initializers and Pattern Matching in Swift.  While that post is named “Class initializers” and Strings are structs, all that is shown in that post works the same for structs.  There are some differences, but I don’t believe they are covered in that post.

I hope you found this article helpful.  If you did, please don’t hesitate to share this post on Twitter or your social media of choice, every share helps.  Of course, if you have any questions, don’t hesitate to contact me on the Contact Page, or on Twitter @CodingExplorer, and I’ll see what I can do.  Thanks!

Sources

  • The Swift Programming Language – Apple Inc.

Filed Under: Swift

Subscribe to the Coding Explorer Newsletter

* indicates required

Follow Us

Facebooktwitterrss

Recent Posts

  • Error Handling in Swift
  • Creating and Modifying a URL in your Swift App
  • Watch Connectivity in Swift — Application Context
  • watchOS Hello World App in Swift
  • API Availability Checking in Swift

Categories

  • Class Reference
  • General
  • Interface Builder
  • My Apps
  • Objective-C
  • Swift
  • Syntax
  • Tutorial
  • Uncategorized

Archives

  • May 2016
  • March 2016
  • February 2016
  • December 2015
  • July 2015
  • June 2015
  • April 2015
  • February 2015
  • January 2015
  • December 2014
  • November 2014
  • October 2014
  • September 2014
  • August 2014
  • July 2014
  • June 2014
  • May 2014
  • April 2014
  • March 2014
  • January 2014
  • November 2013
  • September 2013
  • August 2013
  • July 2013
  • Terms Of Use
  • Privacy Policy
  • Affiliate Disclaimer

Subscribe to the Coding Explorer Newsletter

* indicates required

Copyright © 2025 Wayne Media LLC · Powered by Genesis Framework · WordPress