Swift character


Release date:2023-11-29 Update date:2023-12-08 Editor:admin View counts:234

Label:

Swift character

The character of Swift is a single character string literal, and the data type is Character .

The following example lists two character instances:

import Cocoa

let char1: Character = "A"
let char2: Character = "B"

print("The value of char1 is \(char1)")
print("The value of char2 is \(char2)")

The output of the above program execution is as follows:

The value of char1 is A
The value of char2 is B

If you want to Character if more characters are stored in the constant of type (character), the program execution will report an error, as shown below:

import Cocoa

// The following assignments in Swift will result in an error message
let char: Character = "AB"

print("Value of char \(char)")

The output of the above program execution is as follows:

error: cannot convert value of type 'String' to specified type 'Character'
let char: Character = "AB"

Null character variable

Cannot create empty in Swift Character type variable or constant:

import Cocoa

// The following assignments in Swift will result in an error message
let char1: Character = ""
var char2: Character = ""

print("The value of char1 \(char1)")
print("The value of char2 \(char2)")

The output of the above program execution is as follows:

 error: cannot convert value of type 'String' to specified type 'Character'
let char1: Character = ""
                       ^~
error: cannot convert value of type 'String' to specified type 'Character'
var char2: Character = ""

Traverse characters in a string

Swift’s String type represents a specific sequence Character a collection of type values. Each character value represents a Unicode characters.

In Swift 3 String need to pass through characters the property method to be called, which is available in Swift 4 through the String the object itself is called directly, for example:

In Swift 3:

import Cocoa

for ch in "Runoob".characters {
    print(ch)
}

In Swift 4:

import Cocoa

for ch in "Runoob" {
    print(ch)
}

The output of the above program execution is as follows:

R
u
n
o
o
b

String concatenation character

The following example demonstrates the use of the String of append() method to implement string concatenation characters:

import Cocoa

var varA:String = "Hello "
let varB:Character = "G"

varA.append( varB )

print("varC  =  \(varA)")

The output of the above program execution is as follows:

varC  =  Hello G

Powered by TorCMS (https://github.com/bukun/TorCMS).