For loop in function declaration

102 views Asked by At

I am currently working on iOS app w/ Beacons (Estimote, if it matters).

I downloaded Estimote SDK with code examples, modified them to fullfill my needs, however they hardcode list of devices there, which I can't find a way to modify.

To clarify, following func adds BeaconID:

  self.proximityContentManager = ProximityContentManager(
        beaconIDs: [
            BeaconID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D", major: 12461, minor: 34159),
            BeaconID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D", major: 37813, minor: 3),
            BeaconID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D", major: 33562, minor: 37486),
        BeaconID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D", major: 5913, minor: 4),
        ],

        beaconContentFactory: CachingContentFactory(beaconContentFactory: BeaconDetailsCloudFactory()))

My problem is that I have 3 arrays in a struct where I store Beacons data:

struct BeaconsStruct {
    static var uuidT: [String] = []
    static var minorT: [String] = []
    static var majorT: [String] = []
}

I'm wondering how can I run for loop with BeaconID function and UUID, major, minor set as variable which will load Beacon list from my arrays, not hardcode them directly in the code. This is important because a part of my app fetches Beacon's list from JSON and puts this in a struct above.

2

There are 2 answers

1
Sweeper On

This might not be the fastest solution, but it works and is simple:

Assuming that these three arrays will all be the same length:

static var uuidT: [String] = []
static var minorT: [String] = []
static var majorT: [String] = []

you loop through all three of them at the same time and create BeaconID objects:

var beaconIDs = [BeaconID]()
for i in 0..<uuidT.count {
    beaconIDs.append(BeaconID(UUIDString: uuidT[i], major: Int(majorT[i])!, minor: Int(minorT[i])!))
}

Then, you can create your proximity content manager:

self.proximityContentManager = ProximityContentManager(
        beaconIDs: beaconIDs,
        beaconContentFactory: CachingContentFactory(beaconContentFactory: BeaconDetailsCloudFactory()))
0
Alain T. On

This can be done in a "declarative" way without using a for loop:

var beaconIDs = uuidT.enumerated().map
                { BeaconID(UUIDString: $1, major: Int(majorT[$0])!, minor: Int(minorT[$0])!) }

or, if you like to keep type casting/conversions out of function calls:

var beaconIDs = zip(majorT.map{Int($0)!}, minorT.map{Int($0)!}).enumerated().map 
                { BeaconID(UUIDString: uuidT[$0], major: $1.0, minor: $1.1) }

I would personally prefer storing the minorT and majorT array in their appropriate (Int) type and just use:

var BaconIDs = uuidT.indices.map
               { BeaconID(UUIDString: uuidT[$0], major: majorT[$0], minor: minorT[$0]) }