字符串拼接
- joined() 拼接字符串数组里的所有元素为一个字符串
- joinde(separator:) 以给定的分隔符拼接字符串数组里的所有元素为一个字符串
var array = ["hello", "world"]
print(array.joined())
print(array.joined(separator: ","))
运行结果如下:
helloworld
hello,world
元素为 Sequence 数组的拼接
- joined() 拼接数组里的所有元素为一个更大的Sequence
- joined(separator:) 以给定的分隔符拼接数组里的所有元素为一个更大的Sequence
let ranges = [0..<3, 8..<10, 15..<17]
for range in ranges {
print(range)
}
for i in ranges.joined() {
print(i)
}
运行结果如下:
0..<3
8..<10
15..<17
0
1
2
8
9
15
16
let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let joined = nestedNumbers.joined(separator: [-1, -2])
print(joined)
print(Array(joined))
运行结果如下:
JoinedSequence<Array<Array<Int>>>(_base: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], _separator: ContiguousArray([-1, -2]))
[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]
系统不提供非 Sequence 数组的拼接操作,需要自己实现。【元素为元组类型时,就不支持】
网友评论