简体   繁体   中英

Swift 3 build array (Don't know how to describe)

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM