Reputation: 95
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;
}
Upvotes: 0
Views: 1353
Reputation: 12190
That is how struct
s 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
.
Upvotes: 2