如何在 Swift 中连接或合并数组? [英] How do I concatenate or merge arrays in Swift?

查看:63
本文介绍了如何在 Swift 中连接或合并数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果像这样在 swift 中创建了两个数组:

If there are two arrays created in swift like this:

var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]

如何将它们合并到[1, 2, 3, 4, 5, 6]?

推荐答案

可以用 + 将数组连接起来,构建一个新的数组

You can concatenate the arrays with +, building a new array

let c = a + b
print(c) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

或使用 +=(或 append)将一个数组附加到另​​一个数组:

or append one array to the other with += (or append):

a += b

// Or:
a.append(contentsOf: b)  // Swift 3
a.appendContentsOf(b)    // Swift 2
a.extend(b)              // Swift 1.2

print(a) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

这篇关于如何在 Swift 中连接或合并数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆