0

Trying to learn how to use structs in a class. I have a view controller in which I want to be able to switch a collection view data provider from two different sources so I set up dataprovider struct as such:

struct DataProvider {
    var apiPath: String
    var items: Array<CollectionItem>
    var pagination: Pagination
}

then I am creating two providers in my class such:

let dataProvider1 = DataProvider(apiPath: "1", items: [], pagination: Pagination(currentPage: 1, totalPages: 1, itemsPerPage: 20))
let dataProvider2 = DataProvider(apiPath: "2", items: [], pagination: Pagination(currentPage: 1, totalPages: 1, itemsPerPage: 20) )

I want to be able to store the current provider in a variable:

var currentDataProvider: DataProvider?

Everytime I assign the variable it creates a new dataprovider though

switch sender.selectedSegmentIndex {
    case 0:
        currentDataProvider = self.dataProvider1
    case 1:
        currentDataProvider = self.dataProvider2
    default:
        break;
}

1 Answer 1

2

That is how structs work in Swift. struct is passed by value, while class is passed by reference. If you need to access same instance of DataProvider then define it as class.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.