Addition operator for swift array usage: array1 + = Array2

Source: Internet
Author: User

var stringList1 = [string] ()                                      //Create String type empty array var stringList2 = ["1", "3", "5", "7", "Zoo", "9", "Zoo"]var stringList3: [ String] = ["2", "4", "6", "Apple", "8", "ten"]stringlist1 + = StringList2                                        //Add all elements of the STRINGLIST2 array to the end of the StringList1 print ("StringList1: \ (stringList1)")                              Output Stringlist1stringlist1 + = StringList3                                     //Add all elements of the STRINGLIST3 array to the end of the StringList1 print ("StringList1: \ ( STRINGLIST1)                              //Output StringList1

Operation Result:

StringList1: ["1", "3", "5", "7", "Zoo", "9", "Zoo"]stringlist1: ["1", "3", "5", "7", "Zoo", "9", "Zoo", "2", "4", "6", "a Pple "," 8 "," 10 "]

The elements of the output above are unordered and can be sorted using the array's sort () method or the sortInPlace () method, unlike

The sort () method has a return value that returns a new array without changing the value of the original array :

Print ("After sort: \ (Stringlist1.sort ())") Print ("StringList1: \ (stringList1)")

Operation Result:

After sort: ["1", "Ten", "2", "3", "4", "5", "6", "7", "8", "9", "Apple", "Zoo", "Zoo"]stringlist1: ["1", "3", "5", "7", "Z Oo "," 9 "," Zoo "," 2 "," 4 "," 6 "," Apple "," 8 "," 10 "]

The sortInPlace () method has no return value and changes the value of the original array :

Stringlist1.sortinplace () Print ("StringList1: \ (stringList1)")

Operation Result:

StringList1: ["1", "Ten", "2", "3", "4", "5", "6", "7", "8", "9", "Apple", "Zoo", "Zoo"]

The + = operator can only be used between arrays and cannot add a single element:

var str = "MyString" StringList1 + = str         //Line error: Binary operator ' + = ' cannot be applied to operands of type ' [String] ' an d ' String '

Addition operator for swift array usage: array1 + = Array2

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.