0

I am reading some values generated by different beacons, let's say beacon 1& beacon 2. I want to collect values of each beacon separately.

I think if there is a way to use a where statement would be easier like get values where beacon = 1 and then where beacon = 2

As far as I'm understanding: First, I created the multidirectional array:

var values = [[Int]]()
var tempBeacon = [Int]

Then, a for loop to collect some values for i beacons:


for i in 0...beaconCount-1 {
   let beacon = beacons[i]
   values[i] = tempBeacon.append(beacons[i].value)
}

Thank you guys, and excuse my programming skills as I'm a beginner.

1 Answer 1

2

I would tend to approach this problem as a dictionary of arrays. Each key in the dictionary would represent the beacon and the array stored at each key would contain the values for that beacon. Using a dictionary makes it easy to find the beacon for which you need to add a new entry.

Here's functional example from a playground:

func addBeaconEntry(beaconName: String, newValue: Int) {
    if beaconData[beaconName] == nil {
        // Beacon is not yet in dictionary, so we create an array
        beaconData[beaconName] = [Int]()
    }
    beaconData[beaconName]?.append(newValue)
}

// Dictionary of array of integers for beacon values
var beaconData = [String: [Int]]()
addBeaconEntry(beaconName: "beacon 1", newValue: 10)
addBeaconEntry(beaconName: "beacon 2", newValue: 20)
addBeaconEntry(beaconName: "beacon 3", newValue: 30)
addBeaconEntry(beaconName: "beacon 1", newValue: 1120)

print(beaconData)
print("Data for beacon 1:")
print(beaconData["beacon 1"] ?? [0])

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, exactly the peace I was missing. I like your approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.