O'Reilly logo

Beginning Swift Programming by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required