SoFunction
Updated on 2025-04-06

Swift string types and common methods detailed explanation

Swift string types and common methods

1. Construct

// Direct assignmenttext = ""

// 1. Constructing methodtext = String() // ""
// String constructiontext = String("William") // "William"
// Integer structuretext = String(888) // "888"
// Floating point structuretext = String(8.88) // "8.88"
// Character constructiontext = String("a") // "a"
// Boolean structuretext = String(true) // "true"
// Tuple constructiontext = String(describing: (5, 5.0, true)) // "(5, 5.0, true)"
// List constructiontext = String(describing: [1, 2, 3, 4]) // "[1, 2, 3, 4]"
// Format stringtext = String(format: "Hello, %@", "William") // "Hello, William"

2. Splicing

var text1 = "hello, "
var text2 = "William"
var result = text1 + text2
print(result) // hello, William

// 3. Insert a simple value into a string using \() , similar to ${} in Kotlinvar target = "Hello, \(66)" // Hello, 66

var target2 = "Hello, \(text2)" // Hello, William

var target3 = "Hello, \(1 + 2)" // hellow, 3

3. Characters

var char : Character = "e" // "e"
var char2 = Character("e") // "e"
// Takes up 16 bytesvar size = MemoryLayout<Character>.size // 16
// Character arrayvar array : [Character] = ["W", "i", "l", "l", "i", "a", "m"]
// Construct Stringvar newStr = String(array) // William
// traverse stringslet city = "Shanghai"
for cha in city {
    print(cha)
}

4. Escape characters

Escape characters are often used for typography

// \0: indicates a blank sign// \\: means backslash// \t: indicates tab characters// \n: indicates line break// \r: means carriage return// \': means single quotes// \": means double quotes// \u{}: Create characters with Unicode codevar code = "\u{0068}\u{0065}\u{006c}\u{006c}\u{006f}" // hello
var escapeChar = "Blank character:\0 backslash:\\tTab character:\tLine newline character\nCarriage return character:\rSingle quotes:\'Double quotes:\""
print(escapeChar)

5. Common methods

// string is emptyvar emptyStr = ""
if  {
    print("string is empty")
}
if  == 0 {
    print("string count is 0")
}

// The character size will be compared one by one.let str1 = "100a", str2 = "101a"
if (str1 < str2) {
    print("str1 < str2")
}
// The strings are judged equally, and the positions of all characters are compared to be equal to the strings.if (str1 == str2) {
    print("str1 < str2")
}

// Use subscript to access charactersvar indexStr = "Hello, William"
// Get the starting subscriptvar startIndex:  = 
var endIndex:  = 
// Get the character corresponding to a subscript after a subscriptvar afterChar = indexStr[(after: startIndex)] // e
// Get the character corresponding to the previous subscript of a subscriptvar beforeChar = indexStr[(before: endIndex)] // m

// ... operator specifies the range, moves 4 bits backward from startIndex to intercept substringvar subStr = indexStr[startIndex...(startIndex, offsetBy: 4)] // hello
// Move 7 bits forward from endIndex to intercept substringvar subStr2 = indexStr[(endIndex, offsetBy: -7)..<endIndex] // William

// Get rangevar range = (of: "Hello")
// Append string(Character("."))
(" append string") // Hello, William. append string

// Insert a single character to the specified position Hello, William.# append string("#", at: (startIndex, offsetBy: 15))

// Insert a set of characters Hello, William.-#-# append string(contentsOf: ["-", "#", "-"], at: (startIndex, offsetBy: 15))

// Replace the string in the specified range How are you.-#-# append string(startIndex...(startIndex, offsetBy: 13), with: "How are you")

// Delete a single character in the specified location How are you.-#-# append strin(at: (before: ))

// Delete the specified range -#-# append string(...(, offsetBy: 11))

// Delete all characters ""()

// Convert casevar uppercase = "hello, swift".uppercased() // HELLO, SWIFT
var lowercase = "HELLO, SWIFT".lowercased() // hello, swift

// Check the suffixvar hasPrefix = ("he") // false
var hasSuffix = ("ft") // true

GitHub source code:

This is the end of this article about the detailed explanation and summary of Swift string types and common methods. For more related Swift string content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!