Answers to Swift: Difference between addingObjects method vs append method ( 2 )

  1. 2017-01-01 20:01
    myItemArray.addingObjects(from: [itemTextField.text!]) // Using NSArray


    myItemArray.append(contentsOf: [itemTextField.text!]) // Using Swift Array class

    Is adding the contents of an array to the array, while

    myItemArray.addObject(itemTextField.text!) //NSArray uses addObject not append


    myItemArray.append(itemTextField.text!) //With base Swift Array class

    is adding just an object.

    The first one is would be the equivalent of looping through the array and then calling addObject or append.

    For example, if you were trying to add the contents of the array [1, 2, 3] you could call addingObjects, or loop through the array and call addObject or append.

  2. 2017-01-01 20:01

    There are two things to understand here.

    • First, Swift Array is bridged to Objective-C NSArray. Therefore, many Cocoa Foundation NSArray methods just magically spring to life as if they belonged to Array, and if they don't, you can make them do so by casting a Swift Array to NSArray. For example:

      let arr = ["Manny", "Moe", "Jack"] // Swift Array
      let s = (arr as NSArray).componentsJoined(by:", ") // Cocoa Foundation method
      // s is "Manny, Moe, Jack"
    • Second, Objective-C NSArray, unlike Swift Array, is immutable. To mutate it, as with add or addObjects(from:), you would need an NSMutableArray, which is different class (actually a subclass of NSArray).

    Given all that, ask yourself whenever thinking of using NSArray or NSMutableArray: is this really necessary? In many situations, calling upon the Foundation methods of NSArray or NSMutableArray is completely unnecessary. You are using Swift, so you should use Swift Arrays wherever possible. You can append to a Swift Array with Swift methods, like append and append(contentsOf:), as long as it is declared with var; so stick with those as much as possible.

    Thus, NSMutableArray methods such as add or addObjects(from:) should be of no interest to you.

    Indeed, the example I already gave of bridging is completely unnecessary, as Swift has a similar method:

    let arr = ["Manny", "Moe", "Jack"] // Swift Array
    let s = arr.joined(separator: ", ") // Swift method

Leave a reply to - Swift: Difference between addingObjects method vs append method

◀ Go back