访问和操作数组:拼接操作

2021-07-04  本文已影响0人  一个栗

字符串拼接

var array = ["hello", "world"]
print(array.joined())
print(array.joined(separator: ","))

运行结果如下:
helloworld
hello,world

元素为 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 数组的拼接操作,需要自己实现。【元素为元组类型时,就不支持】

上一篇下一篇

猜你喜欢

热点阅读