Swift 字符串
Swift 字符串是一系列字符的集合。例如 "Hello, World!" 这样的有序的字符类型的值的集合,它的数据类型为 String。
创建字符串
你可以通过使用字符串字面量或 String 类的实例来创建一个字符串:
import Cocoa
// 使用字符串字面量
var stringA = "Hello, World!"
print( stringA )
// String 实例化
var stringB = String("Hello, World!")
print( stringB )
以上程序执行输出结果为:
Hello, World!
Hello, World!
空字符串
你可以使用空的字符串字面量赋值给变量或初始化一个String类的实例来初始值一个空的字符串。 我们可以使用字符串属性 isEmpty 来判断字符串是否为空:
import Cocoa
// 使用字符串字面量创建空字符串
var stringA = ""
if stringA.isEmpty {
print( "stringA 是空的" )
} else {
print( "stringA 不是空的" )
}
// 实例化 String 类来创建空字符串
let stringB = String()
if stringB.isEmpty {
print( "stringB 是空的" )
} else {
print( "stringB 不是空的" )
}
以上程序执行输出结果为:
stringA 是空的
stringB 是空的
字符串常量
你可以将一个字符串赋值给一个变量或常量,变量是可修改的,常量是不可修改的。
import Cocoa
// stringA 可被修改
var stringA = "菜鸟教程:"
stringA += "http://www.runoob.com"
print( stringA )
// stringB 不能修改
let stringB = String("菜鸟教程:")
stringB += "http://www.runoob.com"
print( stringB )
以上程序执行输出结果会报错,因为 stringB 为常量是不能被修改的:
error: left side of mutating operator isn't mutable: 'stringB' is a 'let' constant
stringB += "http://www.runoob.com"
字符串中插入值
字符串插值是一种构建新字符串的方式,可以在其中包含常量、变量、字面量和表达式。 您插入的字符串字面量的每一项都在以反斜线为前缀的圆括号中:
import Cocoa
var varA = 20
let constA = 100
var varC:Float = 20.0
var stringA = "\(varA) 乘于 \(constA) 等于 \(varC * 100)"
print( stringA )
以上程序执行输出结果为:
20 乘于 100 等于 2000.0
字符串连接
字符串可以通过 + 号来连接,实例如下:
import Cocoa
let constA = "菜鸟教程:"
let constB = "http://www.runoob.com"
var stringA = constA + constB
print( stringA )
以上程序执行输出结果为:
菜鸟教程:http://www.runoob.com
字符串长度
字符串长度使用 String.count 属性来计算,实例如下:
Swift 3 版本使用的是 String.characters.count
import Cocoa
var varA = "www.runoob.com"
print( "\(varA), 长度为 \(varA.count)" )
以上程序执行输出结果为:
www.runoob.com, 长度为 14
字符串比较
你可以使用 == 来比较两个字符串是否相等:
import Cocoa
var varA = "Hello, Swift!"
var varB = "Hello, World!"
if varA == varB {
print( "\(varA) 与 \(varB) 是相等的" )
} else {
print( "\(varA) 与 \(varB) 是不相等的" )
}
以上程序执行输出结果为:
Hello, Swift! 与 Hello, World! 是不相等的
Unicode 字符串
Unicode 是一个国际标准,用于文本的编码,Swift 的 String 类型是基于 Unicode建立的。你可以循环迭代出字符串中 UTF-8 与 UTF-16 的编码,实例如下:
import Cocoa
var unicodeString = "菜鸟教程"
print("UTF-8 编码: ")
for code in unicodeString.utf8 {
print("\(code) ")
}
print("\n")
print("UTF-16 编码: ")
for code in unicodeString.utf16 {
print("\(code) ")
}
以上程序执行输出结果为:
UTF-8 编码:
232
143
156
233
184
159
230
149
153
231
168
139
UTF-16 编码:
33756
40479
25945
31243
字符串函数及运算符
Swift 支持以下几种字符串函数及运算符:
序号 |
函数/运算符 & 描述 |
1 |
isEmpty 判断字符串是否为空,返回布尔值 |
2 |
hasPrefix(prefix: String) 检查字符串是否拥有特定前缀 |
3 |
hasSuffix(suffix: String) 检查字符串是否拥有特定后缀。 |
4 |
Int(String) 转换字符串数字为整型。 实例: let myString: String = "256"
let myInt: Int? = Int(myString) |
5 |
String.count Swift 3 版本使用的是 String.characters.count 计算字符串的长度 |
6 |
utf8 您可以通过遍历 String 的 utf8 属性来访问它的 UTF-8 编码 |
7 |
utf16 您可以通过遍历 String 的 utf8 属性来访问它的 utf16 编码 |
8 |
unicodeScalars 您可以通过遍历String值的unicodeScalars属性来访问它的 Unicode 标量编码. |
9 |
+ 连接两个字符串,并返回一个新的字符串 |
10 |
+= 连接操作符两边的字符串并将新字符串赋值给左边的操作符变量 |
11 |
== 判断两个字符串是否相等 |
12 |
< 比较两个字符串,对两个字符串的字母逐一比较。 |
13 |
!= 比较两个字符串是否不相等。 |
补充:字符串分割数组 -- 基于空格![](https://img-blog.csdnimg.cn/20200806182703501.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTM3MTIzNDM=,size_16,color_FFFFFF,t_70)
Swift 字符(Character)
Swift 的字符是一个单一的字符字符串字面量,数据类型为 Character。
以下实例列出了两个字符实例:
import Cocoa
let char1: Character = "A"
let char2: Character = "B"
print("char1 的值为 \(char1)")
print("char2 的值为 \(char2)")
以上程序执行输出结果为:
char1 的值为 A
char2 的值为 B
如果你想在 Character(字符) 类型的常量中存储更多的字符,则程序执行会报错,如下所示:
import Cocoa
// Swift 中以下赋值会报错
let char: Character = "AB"
print("Value of char \(char)")
以上程序执行输出结果为:
error: cannot convert value of type 'String' to specified type 'Character'
let char: Character = "AB"
空字符变量
Swift 中不能创建空的 Character(字符) 类型变量或常量:
import Cocoa
// Swift 中以下赋值会报错
let char1: Character = ""
var char2: Character = ""
print("char1 的值为 \(char1)")
print("char2 的值为 \(char2)")
以上程序执行输出结果为:
error: cannot convert value of type 'String' to specified type 'Character'
let char1: Character = ""
^~
error: cannot convert value of type 'String' to specified type 'Character'
var char2: Character = ""
遍历字符串中的字符
Swift 的 String 类型表示特定序列的 Character(字符) 类型值的集合。 每一个字符值代表一个 Unicode 字符。
Swift 3 中的 String 需要通过 characters 去调用的属性方法,在 Swift 4 中可以通过 String 对象本身直接调用,例如:
Swift 3 中:
import Cocoa
for ch in "Runoob".characters {
print(ch)
}
Swift 4 中:
import Cocoa
for ch in "Runoob" {
print(ch)
}
以上程序执行输出结果为:
R
u
n
o
o
b
字符串连接字符
以下实例演示了使用 String 的 append() 方法来实现字符串连接字符:
import Cocoa
var varA:String = "Hello "
let varB:Character = "G"
varA.append( varB )
print("varC = \(varA)")
以上程序执行输出结果为:
varC = Hello G
Swift 数组
Swift 数组使用有序列表存储同一类型的多个值。相同的值可以多次出现在一个数组的不同位置中。
Swift 数组会强制检测元素的类型,如果类型不同则会报错,Swift 数组应该遵循像Array<Element>这样的形式,其中Element是这个数组中唯一允许存在的数据类型。
如果创建一个数组,并赋值给一个变量,则创建的集合就是可以修改的。这意味着在创建数组后,可以通过添加、删除、修改的方式改变数组里的项目。如果将一个数组赋值给常量,数组就不可更改,并且数组的大小和内容都不可以修改。
创建数组
我们可以使用构造语法来创建一个由特定数据类型构成的空数组:
var someArray = [SomeType]()
以下是创建一个初始化大小数组的语法:
var someArray = [SomeType](repeating: InitialValue, count: NumbeOfElements)
以下实例创建了一个类型为 Int ,数量为 3,初始值为 0 的空数组:
var someInts = [Int](repeating: 0, count: 3)
以下实例创建了含有三个元素的数组:
var someInts:[Int] = [10, 20, 30]
访问数组
我们可以根据数组的索引来访问数组的元素,语法如下:
var someVar = someArray[index]
index 索引从 0 开始,即索引 0 对应第一个元素,索引 1 对应第二个元素,以此类推。
我们可以通过以下实例来学习如何创建,初始化,访问数组:
import Cocoa
var someInts = [Int](repeating: 10, count: 3)
var someVar = someInts[0]
print( "第一个元素的值 \(someVar)" )
print( "第二个元素的值 \(someInts[1])" )
print( "第三个元素的值 \(someInts[2])" )
以上程序执行输出结果为:
第一个元素的值 10
第二个元素的值 10
第三个元素的值 10
修改数组
你可以使用 append() 方法或者赋值运算符 += 在数组末尾添加元素,如下所示,我们初始化一个数组,并向其添加元素:
import Cocoa
var someInts = [Int]()
someInts.append(20)
someInts.append(30)
someInts += [40]
var someVar = someInts[0]
print( "第一个元素的值 \(someVar)" )
print( "第二个元素的值 \(someInts[1])" )
print( "第三个元素的值 \(someInts[2])" )
以上程序执行输出结果为:
第一个元素的值 20
第二个元素的值 30
第三个元素的值 40
我们也可以通过索引修改数组元素的值:
import Cocoa
var someInts = [Int]()
someInts.append(20)
someInts.append(30)
someInts += [40]
// 修改最后一个元素
someInts[2] = 50
var someVar = someInts[0]
print( "第一个元素的值 \(someVar)" )
print( "第二个元素的值 \(someInts[1])" )
print( "第三个元素的值 \(someInts[2])" )
以上程序执行输出结果为:
第一个元素的值 20
第二个元素的值 30
第三个元素的值 50
遍历数组
我们可以使用for-in循环来遍历所有数组中的数据项:
import Cocoa
var someStrs = [String]()
someStrs.append("Apple")
someStrs.append("Amazon")
someStrs.append("Runoob")
someStrs += ["Google"]
for item in someStrs {
print(item)
}
以上程序执行输出结果为:
Apple
Amazon
Runoob
Google
如果我们同时需要每个数据项的值和索引值,可以使用 String 的 enumerate() 方法来进行数组遍历。实例如下:
import Cocoa
var someStrs = [String]()
someStrs.append("Apple")
someStrs.append("Amazon")
someStrs.append("Runoob")
someStrs += ["Google"]
for (index, item) in someStrs.enumerated() {
print("在 index = \(index) 位置上的值为 \(item)")
}
以上程序执行输出结果为:
在 index = 0 位置上的值为 Apple
在 index = 1 位置上的值为 Amazon
在 index = 2 位置上的值为 Runoob
在 index = 3 位置上的值为 Google
合并数组
我们可以使用加法操作符(+)来合并两种已存在的相同类型数组。新数组的数据类型会从两个数组的数据类型中推断出来:
import Cocoa
var intsA = [Int](repeating: 2, count:2)
var intsB = [Int](repeating: 1, count:3)
var intsC = intsA + intsB
for item in intsC {
print(item)
}
以上程序执行输出结果为:
2
2
1
1
1
count 属性
我们可以使用 count 属性来计算数组元素个数:
import Cocoa
var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)
var intsC = intsA + intsB
print("intsA 元素个数为 \(intsA.count)")
print("intsB 元素个数为 \(intsB.count)")
print("intsC 元素个数为 \(intsC.count)")
以上程序执行输出结果为:
intsA 元素个数为 2
intsB 元素个数为 3
intsC 元素个数为 5
isEmpty 属性
我们可以通过只读属性 isEmpty 来判断数组是否为空,返回布尔值:
import Cocoa
var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)
var intsC = [Int]()
print("intsA.isEmpty = \(intsA.isEmpty)")
print("intsB.isEmpty = \(intsB.isEmpty)")
print("intsC.isEmpty = \(intsC.isEmpty)")
以上程序执行输出结果为:
intsA.isEmpty = false
intsB.isEmpty = false
intsC.isEmpty = true
补充:
创建数组的方法不推荐使用文章中记载的方法。
推荐:
var names: [String] = []
var lookup: [String: Int] = [:]
不推荐:
var names = [String]()
var lookup = [String: Int]()
Swift 字典
Swift 字典用来存储无序的相同类型数据的集合,Swift 字典会强制检测元素的类型,如果类型不同则会报错。
Swift 字典每个值(value)都关联唯一的键(key),键作为字典中的这个值数据的标识符。
和数组中的数据项不同,字典中的数据项并没有具体顺序。我们在需要通过标识符(键)访问数据的时候使用字典,这种方法很大程度上和我们在现实世界中使用字典查字义的方法一样。
Swift 字典的key没有类型限制可以是整型或字符串,但必须是唯一的。
如果创建一个字典,并赋值给一个变量,则创建的字典就是可以修改的。这意味着在创建字典后,可以通过添加、删除、修改的方式改变字典里的项目。如果将一个字典赋值给常量,字典就不可修改,并且字典的大小和内容都不可以修改。
创建字典
我们可以使用以下语法来创建一个特定类型的空字典:
var someDict = [KeyType: ValueType]()
以下是创建一个空字典,键的类型为 Int,值的类型为 String 的简单语法:
var someDict = [Int: String]()
以下为创建一个字典的实例:
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
访问字典
我们可以根据字典的索引来访问数组的元素,语法如下:
var someVar = someDict[key]
我们可以通过以下实例来学习如何创建,初始化,访问字典:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someVar = someDict[1]
print( "key = 1 的值为 \(someVar)" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )
以上程序执行输出结果为:
key = 1 的值为 Optional("One")
key = 2 的值为 Optional("Two")
key = 3 的值为 Optional("Three")
修改字典
我们可以使用 updateValue(forKey:) 增加或更新字典的内容。如果 key 不存在,则添加值,如果存在则修改 key 对应的值。updateValue(_:forKey:)方法返回Optional值。实例如下:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict.updateValue("One 新的值", forKey: 1)
var someVar = someDict[1]
print( "key = 1 旧的值 \(oldVal)" )
print( "key = 1 的值为 \(someVar)" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )
以上程序执行输出结果为:
key = 1 旧的值 Optional("One")
key = 1 的值为 Optional("One 新的值")
key = 2 的值为 Optional("Two")
key = 3 的值为 Optional("Three")
你也可以通过指定的 key 来修改字典的值,如下所示:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict[1]
someDict[1] = "One 新的值"
var someVar = someDict[1]
print( "key = 1 旧的值 \(oldVal)" )
print( "key = 1 的值为 \(someVar)" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )
以上程序执行输出结果为:
key = 1 旧的值 Optional("One")
key = 1 的值为 Optional("One 新的值")
key = 2 的值为 Optional("Two")
key = 3 的值为 Optional("Three")
移除 Key-Value 对
我们可以使用 removeValueForKey() 方法来移除字典 key-value 对。如果 key 存在该方法返回移除的值,如果不存在返回 nil 。实例如下:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var removedValue = someDict.removeValue(forKey: 2)
print( "key = 1 的值为 \(someDict[1])" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )
以上程序执行输出结果为:
key = 1 的值为 Optional("One")
key = 2 的值为 nil
key = 3 的值为 Optional("Three")
你也可以通过指定键的值为 nil 来移除 key-value(键-值)对。实例如下:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
someDict[2] = nil
print( "key = 1 的值为 \(someDict[1])" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )
以上程序执行输出结果为:
key = 1 的值为 Optional("One")
key = 2 的值为 nil
key = 3 的值为 Optional("Three")
遍历字典
我们可以使用 for-in 循环来遍历某个字典中的键值对。实例如下:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict {
print("字典 key \(key) - 字典 value \(value)")
}
以上程序执行输出结果为:
字典 key 2 - 字典 value Two
字典 key 3 - 字典 value Three
字典 key 1 - 字典 value One
我们也可以使用enumerate()方法来进行字典遍历,返回的是字典的索引及 (key, value) 对,实例如下:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
print("字典 key \(key) - 字典 (key, value) 对 \(value)")
}
以上程序执行输出结果为:
字典 key 0 - 字典 (key, value) 对 (2, "Two")
字典 key 1 - 字典 (key, value) 对 (3, "Three")
字典 key 2 - 字典 (key, value) 对 (1, "One")
字典转换为数组
你可以提取字典的键值(key-value)对,并转换为独立的数组。实例如下:
import Cocoa
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)
print("输出字典的键(key)")
for (key) in dictKeys {
print("\(key)")
}
print("输出字典的值(value)")
for (value) in dictValues {
print("\(value)")
}
以上程序执行输出结果为:
输出字典的键(key)
2
3
1
输出字典的值(value)
Two
Three
One
count 属性
我们可以使用只读的 count 属性来计算字典有多少个键值对:
import Cocoa
var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
print("someDict1 含有 \(someDict1.count) 个键值对")
print("someDict2 含有 \(someDict2.count) 个键值对")
以上程序执行输出结果为:
someDict1 含有 3 个键值对
someDict2 含有 2 个键值对
isEmpty 属性
Y我们可以通过只读属性 isEmpty 来判断字典是否为空,返回布尔值:
import Cocoa
var someDict1:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2:[Int:String] = [4:"Four", 5:"Five"]
var someDict3:[Int:String] = [Int:String]()
print("someDict1 = \(someDict1.isEmpty)")
print("someDict2 = \(someDict2.isEmpty)")
print("someDict3 = \(someDict3.isEmpty)")
以上程序执行输出结果为:
someDict1 = false
someDict2 = false
someDict3 = true