简体   繁体   English

如何将数组数据存储到结构中?

[英]How to store array data to struct?

i want to store "1" and "2" in datas1 as well "3" and "4" in datas2.我想在datas1中存储“1”和“2”以及在datas2中存储“3”和“4”。

struct Datas {
    let datas1: String
    let datas2: String
}

 var datas : [String] = ["1","2","3","4"]

To store multiple strings in a variable, you should make it a collection like an array要将多个字符串存储在一个变量中,您应该将其设为一个像array一样的集合

struct Datas {
    let datas1: [String]
    let datas2: [String]
}

then you can assign them like:然后你可以像这样分配它们:

var datas = Datas(
    datas1: ["1","2"],
    datas2: ["3","4"]
    // TODO: Don't forget to handle the rest of elements!)

Update due comments:更新到期评论:

You can define a custom initializer that takes an array and build the struct:您可以定义一个自定义初始化程序,该初始化程序接受一个数组并构建结构:

extension Datas {
    init(array: [String]) {
        datas1 = Array(array.prefix(2))
        datas2 = Array(array.suffix(2))
    }
}

Usage :用法

let datas = Datas(array: ["1", "2", "3", "4"])

An Opinion to the data structure itself :对数据结构本身的看法

It seems like a two-dimensional array is a better fit for these datas:看起来二维数组更适合这些数据:

let datas: [[String]] = [["1", "2"],["3", "4"]]

usage:用法:

print(datas[0]) // ["1", "2"]
print(datas[1]) // ["3", "4"]

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

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