Swift Programming: String and character type variables of Swift

String and character type variables of Swift
String and character type variables of Swift


Apple’s new programming language Swift Swift writing about us in the first chapter of the third section is a discussion about the identity of Prohibition. We have learned about the basic types of Swift Languages, Syntax, Variables and Constants Declared, different types of operators. This chapter will contain details of character and string manipulation.

Characters and Strings:

Like other basic data types (Integer, Float, Double), a character is a data type that stores one byte of data. Character type arrays, on the other hand, are called strings. That is, if more than one character is arranged together in a certain way, then these characters together are called a string. For example: “Steve Jobs”, “Swift”, “Programming”, “Macbook Pro and My iPhone” etc. Many times a character can be used as a string and we will see an example later.

Manipulating strings and characters in Swift is much faster than other programming languages ​​and stores Unicode characters in Swift characters. This means that Unicode can be stored as a value on any character which has reduced the hassle of encoding decoding. String manipulation in Swift language is very easy. Constants, characters, numbers, expressions, etc. can be easily inserted into any index of any string. Thus inserting something into a string is called interpolation.

Declaring a String:

We learned in the first chapter how to declare variables and constants. Similarly, we have to declare the string type variable or constant.

let stringVariable = "Any Unicode supported characters"
let anotherStringVariable: String = "Yosemite is the name of latest OS X"

Since string variable and another string variable are initialized with string, both of these constants will now act as string type constants. And all string operations can be performed on them.

Anything other than a string A character can be:

All types of special escaped characters such as ull \ 0 (null), \ n (new line), \\ (backslash), \ t (horizontal tab), \ “(double quote), \ ‘(single quote), etc. .

One Byte Unicode Scalar (xnn, nn can be replaced by any two hexadecimal digits)

The Unicode scalar of two bytes (any four hexadecimal digits can replace n xnnnn, nnnn)

Four bytes of Unicode Scalar (can accommodate up to eight hexadecimal digits in place of \ xnnnnnnnn, nnnnnnnn)

let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\x24"        // $,  Two Byte Unicode scalar U+0024
let blackHeart = "\u2665"      // ♥,  Four Byte Unicode scalar U+2665
let sparklingHeart = "\U0001F496"  // 💖, Eight Byte Unicode scalar U+1F496

Initializing a blank string:

Usually a blank string is initialized at the beginning of the program which later carries any money or information through a collection of large size characters through different operations at different times. This empty string can be initialized in two ways. Empty strings are initialized by assigning a blank string directly to a variable or constant or initializing a new instance of the string type. Below are examples of two types of methods:

var Fancastring = ""               // empty string literal
var emptyString = ""
var anotherEmptyString = String()  // initialiser syntax
// these three strings are all empty, and are equivalent to each other

If necessary, you can easily check the boolean value of the isEmpty property to see if any strings are empty.

var emptyString = ""
if emptyString.isEmpty {
    println("Nothing to see here")
// prints "Nothing to see here"

String Mutability: Whether a string is mutable or modifiable is determined when declaring a variable or constant. If the string is declared as “var” then it can be modified. But if this string is type “let” then it will behave like a constant. So the “let” type string is not mutable. If you look at the following example, the matter will become clear.

var variableString = "Swift is"
variableString += " a new programming language."
// variableString is now "Swift is a new programming language."

let constantString = "Swift is very much"
constantString += " faster and interactive"
// this reports a compile-time error - a constant string cannot be modified

This string of Swift has a bridge connection with the NSString of Objective-C. If we work with Cocoa or Cocoa Touch’s Foundation class, all Swift API’s NSString class APIs can be called for Swift’s string type variables.

If the function or method is sent to the NSString instance of the Cocoa or Cocoa Touch’s Foundation class, then it is sent to the reference or pointer of the string that is assigned to the new pointer or reference. No copy of the original string is made. Swift, on the other hand, creates a string value. If it is assigned to a variable or sent to a method or function, then first a copy of that string is created and then this new string is sent to the method or assigned to a new variable. There will be more details about this in our paper book.

Character Manipulation:

By now we know that strings are actually a series of characters that are represented by a string type in Swift. Each Character is again a Unicode character. In Swift, each character of a string can be accessed with a for-in loop. The syntax and details of the for-in loop will be in the next chapter. At this point we will access all the Characters from the beginning to the end of a string and see it.

for ch in "Macintosh" {
// M
// a
// c
// i
// n
// t
// o
// s
// h

To declare a character type variable or constant from a string of one of the characters, you have to write the following code.

let charConstant: Character = "$"
var charVariable: Character = "k"

Know the total number of characters in the string:

Count elements () is a global method that takes a string as an argument and returns how many characters it contains in the string.

let intro: String = "In Swift, It is too easy to count characters."
var countChar = countElements(intro);
println(countChar)  // 45

Note: The characters in Swift’s strings are Unicode characters, and the sizes of different characters in Unicode vary. That is why not all characters in Swift language take the same size of memory. So the return value of the count elements () method is not what we want it to be. So to know the exact number of characters in a string, you have to calculate each character using a loop. In the following example, counter variable 0 is initialized in the first line. Then each character is visited from the beginning to the end with a for-in loop and the value of the counter is increased by 1 each time. As a result, the total number of “Macintosh” characters in the counter variable will be found when the execution of the for-in is over.

var counter = 0
for ch in "Macintosh" {
println("This string has \(counter) characters"); // This string has 9 characters

Concrete strings and characters:

The concatenation of string and character type variables or constants can be used to initialize a new string. Again, a string can be modified by modifying the string by adding a character to it. The issues can be understood by looking at the following examples.

//Example 1
let string1 = "hello"
let string2 = " Steve"
let character1: Character = "!"
let character2: Character = "?"

let stringPlusCharacter = string1 + character1        // equals "hello!"
let stringPlusString = string1 + string2              // equals "hello Steve"
let characterPlusString = character1 + string1        // equals "!hello"
let characterPlusCharacter = character1 + character2  // equals "!?"

//Example 2
var instruction = "follow"
instruction += string2
// instruction now equals "follow Steve"

var welcome = "good morning"
welcome += character1
// welcome now equals "good morning!"

String Interpolation:

String interpolation is called creating a new string by combining a constant, variable, expression, etc. into a string. For this, the new variable or constant or expression to be mixed has to be written inside the parentheses or “()” and given a backslash before it. Then the new thing is inserted in this part of the string.

let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"

A new string message has been created using the multiplier constant twice in the above code. This is where multiplier values ​​will be inserted where the multiplier is written with a backslash and then a parenthesis. Instead of “multiplier” during interpolation, the value of multiplier here will be 3. The point to note here is that the first multiplier is a constant inserted directly into the string. But the expression “Double (multiplier) * 2.5” is inserted in the 2nd. First the value of the multiplier is doubled with Cast and then multiplied by 2.5 to get the result that has been inserted into the string.

String Comparison:

There are 3 methods to compare between the string type of Swift: String Equality, Prefix Equality and Suffix Equality.

2 strings will be equal if and only if the characters of both strings are the same and in the same order. In this case, it should be kept in mind that since the upper case letter and the lower case letter Unicode are different, they will also be different as characters.

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
// prints "These two strings are considered equal"
The prefix or has suffix method is used to check if a string has a particular string prefix or suffix. Both methods return a boolean value with a string type argument. Method two checks whether each character in the argument is in the same order in the main string.
let comment = "Swift is a awesome language."
if comment.hasPrefix("Swift"){
   // String comment contains a "Swift" as prefix

if comment.hasSuffix("language."){
   // String comment contains a "language." as Suffix

In the above example, the comment is a string type constant. The prefix (“Swift”) method is basically the first “Swift” string of the comment string. Since the comment string has “Swift” as the prefix, the method returns TRUE. Again the has suffix (“language.”) Method is checking that the comment string is “language.” Whether it ended with Since the end of the string is “language.” So, the method returns TRUE.

Case conversion:

Case conversion is a common task of string manipulation. That is, transforming from lowercase to uppercase or uppercase to lowercase. This work can be done quite easily in Swift.

let normal = "Would you mind giving me a glass of Water?"
let uppercase = normal.uppercaseString
// uppercase is equal to "WOULD YOU MIND GIVING ME A GLASS OF WATER?"
let lowercase = normal.lowercaseString
// lowercase is equal to "would you mind giving me a glass of water?"

Conclusion: You must have noticed that we are pronouncing the word Unicode over and over again. Swift has a special method for string and character handling that allows you to easily manipulate string and character’s Unicode representation. Details about this can be found in our paper book.

Note: More Info (Tech24InfoBD) (Swift programming language)


Please enter your comment!
Please enter your name here