# 字符串

`Swift`的`String`和`Character`类型提供了一种快速且兼容Unicode的方式来处理代码中的文本内容。

> `Swift` 的 `String` 类型与 `Foundation NSString` 类进行了无缝桥接。`Foundation` 还对 `String` 进行扩展使其可以访问 `NSString` 类型中定义的方法。这意味着调用那些 `NSString` 的方法，你无需进行任何类型转换。

## 1. 字符串字面值

```swift
let someString = "Hello World"

```

## 2.字符串字面量的特殊字符

* 转义字符

  ```
     \0(空字符)、\\(反斜线)、\t(水平制表符)、\n(换行符)、\r(回车符)、\"(双引号)、\'(单引号)
  ```
* Unicode 标量

  ```
    写成 \u{n}(u 为小写)，其中 n 为任意一到八位十六进制数且可用的 Unicode 位码。
  ```

```swift
let dollarSign = "\u{24}"             // $，Unicode 标量 U+0024
let blackHeart = "\u{2665}"           // ♥，Unicode 标量 U+2665
let sparklingHeart = "\u{1F496}"      // 💖，Unicode 标量 U+1F496

```

## 3. 多行字符串

`Swift`可以使用`“”“`包含多行字符串，直接回车表示换行，不用表示换行，在多行字符串中可以直接使用`"`

```swift

let str = """
      hdakshdajshdkajs\n
\u{1234}
            dasdjaskjdklasjdkals
   dsahjdkhasjkdhaskj
"""
/* 
  str值为：

      hdakshdajshdkajs

ሴ
            dasdjaskjdklasjdkals
   dsahjdkhasjkdhaskj
*/

```

## 4. 扩展字符串分隔符

将字符串放在引号`"`中并用数字符号`#`括起来。字符串中的特殊字符将会被直接包含而非转义后的效果。

```swift
let str = #"""
      hdakshdajshdkajs\n
\u{1234}
            dasdjaskjdklasjdkals
   dsahjdkhasjkdhaskj
"""#

/**

str值为：

      hdakshdajshdkajs\n
\u{1234}
            dasdjaskjdklasjdkals
   dsahjdkhasjkdhaskj

**/


let str2 = #"""
Here are three more double quotes: """
"""#

/**

str2值为：

Here are three more double quotes: """

**/

```

## 6. 初始化空的字符串

```swift
var str = ""      // 可变字符串

let str1 = String()   // 常量字符串
```

## 7. 字符串是值类型

在 `Swift` 中 `String` 类型是值类型。如果你创建了一个新的字符串，那么当其进行常量、变量赋值操作，或在函数/方法中传递时，会进行值拷贝。在前述任一情况下，都会对已有字符串值创建新副本，并对该新副本而非原始字符串进行传递或赋值操作。

在实际编译时，Swift 编译器会优化字符串的使用，使实际的复制只发生在绝对必要的情况下，这意味着你将字符串作为值类型的同时可以获得极高的性能。

## 8. 字符类型

```swift
let c : Character = "c"

let cArray : [Character] = ["c","a","t"]

let catStr = String(cArray)

for c in catStr {
    print(c)
}

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.existorlive.cn/kai-fa-yu-yan-xue-xi/swift/3.-zi-fu-chuan-he-zi-fu/1.-zi-fu-chuan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
