1

First of all, sorry for the unclear title, but I don't know how to describe my problem or how to search for it. (Still a beginner)

So I have an array where I need to put values in.

let heliosDataArray:String = "[{\"timestamp\":\"\(timestamp)\",\"uv\":\"\(uvIndex!)\",\"light\":\"\(lightvalue!)\"}]"

So in this "template" I need to add 3 values: timestamp, uvIndex and lightValue. So far so good. Now I have a lot of values and for an API call I need to to chain this array multiple times in to 1 array, kind of like a master array. What is the most practical way of doing this? The amount of data is variable, and comes from CoreData. Probably going to put the values first in arrays. What should I be searching for? I was thinking a loop but like more advanced?

Thanks in advance

Riyan Fransen
  • 534
  • 1
  • 3
  • 14
  • btw, type of heliosDataArray is String... – Sergey Gamayunov Nov 14 '17 at 10:31
  • You mean you have currently 1 tuple of {timestamp, uvIndex, light} in an array and now you need to add more tuples in the same array? – Syed Qamar Abbas Nov 14 '17 at 10:31
  • I think what you're looking for is an array of custom types - here's a good example. https://stackoverflow.com/questions/28163034/how-to-properly-declare-array-of-custom-objects-in-swift in simple terms, you're going to want to create a custom type for timestamp/uv/lightValue, and then add those to your array – Russell Nov 14 '17 at 10:32
  • Just create an object that have the 3 values to hold in your array – Tj3n Nov 14 '17 at 10:40
  • Why don't you use a regular Swift array which you add data to, instead of using a string. You could then serialize that array into a string when you need the contents of the array as a string. – rodskagg Nov 14 '17 at 10:46

2 Answers2

3

You can approach with object-oriented logic:

struct Data {

    var timestamp: Double?
    var lightValue: Double?
    var uvIndex: Int?
}    

let data1 = Data(timestamp: 13.4, lightValue: 3.4, uvIndex: 4)
let data2 = Data(timestamp: 12.4, lightValue: 2.4, uvIndex: 3)
let data3 = Data(timestamp: 11.4, lightValue: 1.4, uvIndex: 2)

var dataArray = Array<Data>() // or-> var data = [Data]()

dataArray.append(data1)
dataArray.append(data2)
dataArray.append(data3)
memtarhan
  • 144
  • 1
  • 3
2

You can do this in many ways. One of them is shown below let say you have three values from coredata timestamp, uvIndex and lightvalue

Seems what you are asking is a array of dictionaries, first you need is a dictionary of the values you got from CoreData, let call them dayItem

var dayItem = ["timestamp": timestamp, 
               "uv": uvIndex,
               "light": lightValue]

Now create an array of values

var dayArray: [[String: Any]] = []
dayArray.append(dayItem)

Every time you want to append new items just use the append method of array

carbonr
  • 6,049
  • 5
  • 46
  • 73