简体   繁体   English

Swift 3构建数组(不知道如何描述)

[英]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. 因此,在此“模板”中,我需要添加3个值:时间戳记,uvIndex和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. 现在我有很多值,对于API调用,我需要多次将此数组链接到1个数组中,有点像一个主数组。 What is the most practical way of doing this? 最实用的方法是什么? The amount of data is variable, and comes from CoreData. 数据量是可变的,并且来自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 其中之一是显示下面就让我们说,你有从coredata三个值timestampuvIndexlightvalue

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 似乎您要问的是一个字典数组,首先需要的是从CoreData获取的值的字典,我们将其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 每当您要追加新项目时,只需使用array的append方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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