How to use Swift characters
This article mainly explains "how to use Swift characters". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn how to use Swift characters.
Guided Swift is an open source programming language that supports multiple programming paradigms and compilations.
The character of Swift is a single character string literal, and the data type is Character.
The following example lists two character instances:
Import Cocoalet char1: Character = "A" let char2: Character = "B" print ("value of char1 is\ (char1)") print ("value of char2 is\ (char2)")
The output of the above program execution is as follows:
The value of char1 is Achar2 and the value of B
If you want to store more characters in a constant of type Character, the program execution will report an error, as shown below:
The following assignment in import Cocoa// Swift will report an error 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
You cannot create empty Character (character) type variables or constants in Swift:
The following assignment in import Cocoa// Swift reports an error let char1: Character = "" var char2: Character = "" print ("the value of char1 is\ (char1)") print ("the value of char2 is\ (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
The String type of Swift represents a collection of Character (character) type values for a particular sequence. Each character value represents a Unicode character.
Property methods that String in Swift 3 needs to call through characters can be called directly through the String object itself in Swift 4, for example:
In Swift 3:
Import Cocoafor ch in "Runoob" .customers {print (ch)}
In Swift 4:
Import Cocoafor ch in "Runoob" {print (ch)}
The output of the above program execution is as follows:
Runoob
String concatenation character
The following example demonstrates using the append () method of String to implement string concatenation characters:
Import Cocoavar 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 Thank you for your reading, this is the content of "how to use Swift characters". After the study of this article, I believe you have a deeper understanding of how to use Swift characters, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!