SoFunction
Updated on 2025-04-11

Swift Notes String

String

Introduction

The string in a String is a value type, and the value will be copied when passed, while the string passing of NSString is a reference. We can use for in to iterate over strings:

Copy the codeThe code is as follows:

var a : String = "a"
for c in "Hello" {
    println(c)
}

The number of characters in a string can be calculated using countElements:

Copy the codeThe code is as follows:

countElements("1234567") // 7

However, it should be noted that the length of countElements and NSString are not always exactly the same value, because length uses UTF-16 values ​​rather than Unicode characters. For example, after emoji is added, the UTF-16 calculates the result of 2, while the Unicode calculates the result of 1. You can see the following example:

Copy the codeThe code is as follows:

var a = "Hello

The above is the entire content of this article, I hope you like it.