3 Strings and Characters

WHAT YOU WILL LEARN IN THIS CHAPTER:                            

  • How to define a string literal
  • The copy behavior of strings
  • The difference between characters and strings
  • How to use the various special string characters
  • How to use Unicode characters in Swift
  • How to use the various common string functions
  • How type conversion works for strings
  • How the String type interoperates with the NSString class

In the previous chapter, you learned about the various basic data types supported in Swift as well as some of the new features it introduces—tuples, optional types, and enhanced enumerations. In this chapter, you will learn how strings are represented in Swift using the String type and how it is bridged seamlessly with the NSString class found in the Foundation framework in Objective-C. In particular, because Swift supports Unicode natively, there are some areas that you need to pay attention to when dealing with strings. All of these are discussed in this chapter.

STRINGS

In Swift, a string literal is a sequence of characters enclosed by a pair of double quotes (""). The following code snippet shows a string literal assigned to a constant and another to a variable:

let str1 = "This is a string in Swift"        //---str1 is a constant---
var str2 = "This is another string in Swift"  //---str2 is a variable---

Because the compiler uses type inference, there is no need to specify the type of constant and variable that is being assigned the string. However, if you ...

Get Beginning Swift Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.