Swift文档学习(三)

Swift 文档学习——字符串和字符

官方文档(英文):https://docs.swift.org/swift-book/documentation/the-swift-programming-language/
官方文档(中文):https://swiftgg.gitbook.io/swift/

1、字符串字面量

(1)多行字符串字面量

续行符:反斜杠(\)。

let softWrappedQuotation = """
The White Rabbit put on his spectacles.  "Where shall I begin, \
please your Majesty?" he asked.

"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""

(2)字符串字面量的特殊字符

转义字符 \0(空字符)、\(反斜线)、(水平制表符)、(换行符)、(回车符)、"(双引号)、'(单引号)。
Unicode 标量,写成 \u{n}(u 为小写),其中 n 为任意一到八位十六进制数且可用的 Unicode 位码。

let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\u{24}"             // $,Unicode 标量 U+0024
let blackHeart = "\u{2665}"           // ♥,Unicode 标量 U+2665
let sparklingHeart = "\u{1F496}"      // 💖,Unicode 标量 U+1F496

在多行字符串字面量用"“” “”“来表示字符串内容时,(”)则不用转义字符(\),但是里面有(“”")时,需要至少一个转义字符(\),如:

let threeDoubleQuotes = """
Escaping the first quote \"""
Escaping all three quotes \"\"\"
"""

(3)扩展字符串分隔符

let string1 = #"Line 1 \nLine 2"#
// 输出 Line 1 \nLine 2

let string2 = #"Line 1 \#nLine 2"#
// 输出 Line1
// Line2

let string3 = ###"Line1 \###nLine2"###
// 输出 Line1
// Line2

2、初始化空字符串

var emptyString = ""               // 空字符串字面量
var anotherEmptyString = String()  // 初始化方法
// 两个字符串均为空并等价。
if emptyString.isEmpty {
   
    print("Nothing to see here")
}
// 打印输出:“Nothing to see here”

3、字符串可变性

var variableString = "Horse"
variableString += " and carriage"
// variableString 现在为 "Horse and carriage"

let constantString = "Highlander"
constantString += " and another Highlander"
// 这会报告一个编译错误(compile-time error) - 常量字符串不可以被修改。

4、字符串是值类型

Swift 默认拷贝字符串的行为保证了在函数/方法向你传递的字符串所属权属于你,无论该值来自于哪里。你可以确信传递的字符串不会被修改,除非你自己去修改它。

5、使用字符串

for character in "Dog!🐶" {
   
    print(character)
}
// D
// o
// g
// !
// 🐶
let catCharacters: [Character] = ["C", "a", 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值