Swift - Data Type Characters

Introduction

In Swift a string is made up of characters.

You can iterate through a string and extract each character using the For-In loop.

The following code snippet shows an example:

Demo

var helloWorld = "Hello, World!"

for c in helloWorld {
     print(c)//from  w w w  .  j a  v  a  2  s . c om
}

Result

The For-In loop works with Unicode characters as well:

Demo

var hello = ""  //hello contains two Chinese characters
for c in hello {/* www .j  a  v a  2  s .c  om*/
    print(c)
}

By default, using type inference the compiler will always use the String type for a character enclosed with double quotes.

For example, in the following statement, euro is inferred to be of String type:

var euro = "a"

However, if you want euro to be the Character type, you have to explicitly specify the Character type:

var euro:Character  = "c"

To append a string to a character, you need to convert the character to a string, as the following shows:

Demo

var euro:Character = "c"
var price = String(euro) + "2500"  
euro += "2500"         
print(euro)/*  w w  w .  j a v a 2 s . c om*/