Search code examples
arraysswiftstructure

How to store array data to struct?


i want to store "1" and "2" in datas1 as well "3" and "4" in datas2.

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

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

Solution

  • To store multiple strings in a variable, you should make it a collection like an 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"]