Array
8 methods一种有序的、支持随机访问的集合。在 Swift 中数组是值类型。
String.count -> Int在数组末尾添加一个新元素。
Returns
Int
Example
swift
let s = "Hello"
print(s.count) // 5
let cafe = "café"
print(cafe.count) // 4String.uppercased() -> String数组中元素的数量。
Returns
String
Example
swift
let s = "Hello World"
print(s.uppercased()) // "HELLO WORLD"String.lowercased() -> String移除并返回指定位置的元素,同时移动后续元素。
Returns
String
Example
swift
let s = "Hello World"
print(s.lowercased()) // "hello world"String.hasPrefix(_ prefix: String) -> Bool如果数组包含与给定值相等的元素,则返回 true。
Parameters
| Name | Type | Description |
|---|---|---|
| element | String | 要搜索的元素。 |
Returns
Bool
Example
swift
let s = "Hello, World"
print(s.hasPrefix("Hello")) // true
print(s.hasPrefix("World")) // falseString.hasSuffix(_ suffix: String) -> Bool返回一个数组,包含将给定闭包映射到序列元素上的结果。
Parameters
| Name | Type | Description |
|---|---|---|
| transform | String | 映射闭包。 |
Returns
Bool
Example
swift
let s = "Hello, World"
print(s.hasSuffix("World")) // true
print(s.hasSuffix("Hello")) // falseString.contains(_ other: String) -> Bool返回一个数组,包含满足给定谓词的元素。
Parameters
| Name | Type | Description |
|---|---|---|
| isIncluded | String | 谓词闭包。 |
Returns
Bool
Example
swift
let s = "Hello, World"
print(s.contains("World")) // true
print(s.contains("xyz")) // falseString.split(separator: Character) -> [Substring]返回序列的元素,使用给定的比较闭包进行排序。
Parameters
| Name | Type | Description |
|---|---|---|
| by | Character | 比较闭包(默认升序)。 |
Returns
[Substring]
Example
swift
let s = "a,b,c"
let parts = s.split(separator: ",")
// parts == ["a", "b", "c"]String.replacingOccurrences(of: String, with: String) -> String返回一个字符串,包含序列的元素,元素之间由给定的分隔符分隔。
Parameters
| Name | Type | Description |
|---|---|---|
| separator | String | 元素之间的分隔符。 |
| with | String | Replacement string. |
Returns
String
Example
swift
let s = "Hello, World"
let r = s.replacingOccurrences(of: "World", with: "Swift")
// r == "Hello, Swift"