In my ViewModel I'm fetching data from API and I want to populate my variable with the data, however when I declare the variable, it returns error.
ViewModel.swift
class PromoDetailViewModel: ObservableObject, ModelService {
var apiSession: APIService
@Published var dataArray = [BannerDetailResData]() // This is okay
@Published var data = BannerDetailResData // This returns error
// Error message is:
// Expected member name or constructor call after type name
// Add arguments after the type to construct a value of the type
// Use .self to reference the type object
init(apiSession: APIService = APISession()) {
self.apiSession = apiSession
}
func getPromoDetail() {
let cancellable = self.getBannerDetail(bannerID: bannerID)
.sink(receiveCompletion: { result in
switch result {
case .failure(let error):
print("Handle error: \(error)")
case .finished:
break
}
}) { (result) in
if result.statusCode == 200 {
self.data = result.data
}
self.isLoading = false
}
cancellables.insert(cancellable)
}
}
BannerDetailResData.swift
struct BannerDetailResData: Codable, Hashable {
let bannerId: String
let bannerImg: String
let startDate: String
let endDate: String
}
Why is it when I declare as BannerDetailResData, it works perfectly? What is the correct way of declaring this single struct object? Thank you in advance
CodePudding user response:
Make it optional
@Published var data:BannerDetailResData?