1

I have my class defined as:

class Device: Object {
        dynamic public var assetTag = ""
        dynamic var location = ""
    }

I also have two arrays defined as:

let array = ["12", "42", "52", "876"]
let array2 = ["SC", "EDS", "DS", "EF"]

I would like to loop through the first array and add each value to my realm Device.assetTag object and loop through my second array and add each value to the Device.location object.

I tried using the code from the Realm readme to just add data from the first array but it did not seem to loop:

let realmArray = Device(value: array)

let realm = try! Realm()


        try! realm.write {
            realm.add(realmArray)
        }

1 Answer 1

2

You have two arrays one that holds asetTags and Another location so first you have to build the object from those. You can do something like following (probably refactoring needed)

class Device: Object {
   dynamic public var assetTag = ""
   dynamic var location = ""
}

class Test {

   let assetTags = ["12", "42", "52", "876"]
   let locations = ["SC", "EDS", "DS", "EF"]


   func saveDevice() {
      let realm = try! Realm()
      try! realm.write {
         let allDevices = getDeviceArray()
         for device in allDevices {
            realm.add(device)
         }
     }
  }

func getDeviceArray() -> [Device] {
    let requiredDevices = [Device]()
    var index = 0
    for tag in assetTags {
        let locationForTag = locations[index]
        let device = Device()
        device.assetTag = tag
        device.location = locationForTag
        requiredDevices.append(device)
        index += 1
    }
    return requiredDevices
  }

}

Remember to put loop within realm.write for batch operation, this ensure the connection to write is made once.

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

2 Comments

I understand most of what you put but how does let locationForTag = location[index] loop through all the locations? If index is defined as 0 above wouldn't that only pull the first value from the array?
your answer before you added the += 1 worked the exact same. I have no idea how.

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.