Contact Us

Use the form on the right to contact us.

You can edit the text in this area, and change where the contact form on the right submits to, by entering edit mode using the modes on the bottom right. 

Oak Ridge, TN, 37830
United States


Adding/Appending Objects to an Array : Swift 3

Wade Cantley

The goal here is just to demonstrate how to add an object to an array using a real-world example.  The code is commented and includes an example of a NSPredicate filter.

Look for /* # */ to indicate where that happens.

// I am including lots of "stuff" so that it is clear how this came together in a real example.  
// The code won't work without something feeding becaons to the notification system.  But that doesn't matter.
// The important bits will have /*>*/ next to it.
import UIKit
import CoreLocation

class ListBeacons: UITableViewController {

    // /* 1 */ - Create a varriable that will act as your storage container.
    // /* 2 */ - Append CLBeacon objects to the array.
    // Setup the variable that will hold the array [] of objects of the type CLBeacon
    /* 1 */ var nearestBeacons = [CLBeacon]()
    //....later in code
    override func viewDidLoad() {
        //Listen for a message containing an array of beacons
        // This comes from another page that sends the package of beacons every time CoreLocation refreshes its search.
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ListBeacons.getAllBeacons),  name: "sendAllBeacons", object: nil)
    } //viewDidLoad

    func getAllBeacons(notification: NSNotification){
        //clear the array
        nearestBeacons = []
        // Put the package (that contains the beacons) from the notification into a variable
        var packageOfBeacons = Array(arrayLiteral: notification.object!)
        //Put the array of beacons into a variable called "beacons"
        let beacons = packageOfBeacons[0] as! [CLBeacon]
        // loop over that array with the contents of type "CLBeacon"
        for eachBeacon in beacons {
            // Check the proximity, and if it is close move into the IF
            if (eachBeacon.proximity as CLProximity).rawValue == 1 {
                // Filter to see if the beacon already exists in this list.
                let predicate = NSPredicate(format: "%K == %@ AND %K == %@ AND %K == %@" ,
                                            "proximityUUID", eachBeacon.proximityUUID,
                                            "major", eachBeacon.major,
                                            "minor", eachBeacon.minor)
                let sorted = self.nearestBeacons.filter({
                    return predicate.evaluateWithObject($0)
                // If there are no beacons like it in the array, append it.
                if sorted.count == 0 {
                    /* 2 */ self.nearestBeacons.append(eachBeacon)
                    print("Added new one")
    } // getAllBeacons