首页 > 代码库 > Swift数组的加法运算符用法:array1 += array2

Swift数组的加法运算符用法:array1 += array2

var stringList1 = [String]()                                      //创建String类型空数组var stringList2 = ["1", "3", "5", "7", "zoo", "9","zoo"]var stringList3 :[String] = ["2", "4", "6","apple", "8", "10"]stringList1 += stringList2                                        //把stringList2数组的所有元素添加到stringList1的末尾print("stringList1: \(stringList1)")                              //输出stringList1stringList1 += stringList3                                       //把stringList3数组的所有元素添加到stringList1的末尾print("stringList1: \(stringList1)")                              //输出stringList1

运行结果:

stringList1: ["1", "3", "5", "7", "zoo", "9", "zoo"]stringList1: ["1", "3", "5", "7", "zoo", "9", "zoo", "2", "4", "6", "apple", "8", "10"]

以上输出结果的元素无序排列,可使用数组的 sort() 方法或 sortInPlace() 方法排序,两者不同在于

sort()方法返回值,返回一个新数组,而不改变原数组的值:

print("After sort: \(stringList1.sort())")print("stringList1: \(stringList1)")

运行结果:

After sort: ["1", "10", "2", "3", "4", "5", "6", "7", "8", "9", "apple", "zoo", "zoo"]stringList1: ["1", "3", "5", "7", "zoo", "9", "zoo", "2", "4", "6", "apple", "8", "10"]

sortInPlace()方法返回值,会改变原数组的值:

stringList1.sortInPlace()print("stringList1: \(stringList1)")

运行结果:

stringList1: ["1", "10", "2", "3", "4", "5", "6", "7", "8", "9", "apple", "zoo", "zoo"]

 

+=运算符只能用于数组之间,不能添加单个元素:

var str = "myString"stringList1 += str         //此行报错:Binary operator ‘+=‘ cannot be applied to operands of type ‘[String]‘ and ‘String‘  

 

Swift数组的加法运算符用法:array1 += array2