Lokang 

Swift and MySQL

String and Characters

In Swift, String and Character are fundamental types used for storing and manipulating text.

String

A string is an ordered collection of characters enclosed in double quotes ("). Strings are Unicode-compliant, which means they can store any Unicode characters, including emojis.

Creating Strings

var str = "Hello, world"
let constantStr = "You cannot change me"

String Interpolation

let name = "John"
print("Hello, \(name)")

Concatenating Strings

let hello = "Hello, "
let world = "world"
let helloWorld = hello + world

String Methods and Properties

let string = "Hello, world"
// Length
print(string.count)
// Empty check
print(string.isEmpty)
// Append to string
var mutableString = "Hello"
mutableString.append(", world")
// Substring
let index = string.index(string.startIndex, offsetBy: 5)
let substring = string[..<index]  // "Hello"
// Splitting
let words = string.split(separator: " ")

Comparing Strings

if string1 == string2 {
   print("Both strings are equal.")
}

 

 

Character

A Character in Swift is a single character String literal, written by enclosing a single character in double quotes.

Creating Characters

let char: Character = "A"

Appending Characters to String

var word = "hel"
let char: Character = "p"
word.append(char)  // word is now "help"

Counting Characters in a String

let string = "Hello, world"
print("The string has \(string.count) characters.")

Iterating over Characters in a String

for character in "Hello" {
   print(character)
}

Multiline Strings

You can define a string that spans multiple lines by wrapping your text in triple quotes (""").

let multilineString = """
   This is a multi-line string.
   You can write text over multiple lines.
   """

Unicode Support

Swift's String and Character types are Unicode-compliant.

let emoji = "🏡"