1

I'm trying to create a simple data model in Swift. The model is a list, in which it will have items such as name, size, colour and store.

struct List{

var list: [String]
var name: String
var size: String
var colour: String
var store: String

init(var list:[String], name: String, size: String, colour: String, store: String){

    self.list = list
    self.name = name
    self.size = size
    self.colour = colour
    self.store = store

    list = [name, size, colour, store]
}

If I were to put list = [name, size, colour, store] at index 0, only name is there. How do I store multiple values for one index such that

Index 0: name1, size1, colour1, store1

Index 1: name2, size2, colour2, store2

2
  • 1
    Sounds like you want an array of arrays. or An array of objects Commented Feb 17, 2016 at 9:53
  • You're probably mixing up instance vs. type variables. list belongs always to the instance which is created in the init function and contains one item as long as the variable is not accessed from outside the List structure. Commented Feb 17, 2016 at 10:00

2 Answers 2

6

You need to define a model to represent the elements of your list

struct Element {
    let name: String
    let size: String
    let colour: String
    let store: String
}

Creating the list

var list = [Element]()

Adding elements

let elm = Element(name: "name0", size: "size0", colour: "colour0", store: "store0")
list.append(elm)

let anotherElm = Element(name: "name1", size: "size1", colour: "colour1", store: "store1")
list.append(anotherElm)

Extracting an element

let firstElm = list[0] // "name0", "size0", "colour0", "store0"
Sign up to request clarification or add additional context in comments.

Comments

1

swift Tuples, every single Element

struct List{
var list:  [(String, String, String, String)] = []
//    var name: String
//    var size: String
//    var colour: String
//    var store: String

init(name: String, size: String, colour: String, store: String){
    let t = (name, size, colour, store)
    self.list.append(t)
    }
}

or using two struct

    struct Element {
        var name: String
        var size: String
        var colour: String
        var store: String
    }


    struct List2 {
        var list:  [Element] = []

        init(name: String, size: String, colour: String, store: String){
            let t = Element(name: name, size: size, colour: colour, store: store)
            self.list.append(t)
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.