I recently worked on SwiftUI and starting writing code in a declarative way. But here comes a confusion. Like what is shown below, I want to (1)load the song data and (2)show the view by setting isInfoViewShown, after song is assigned to any value.
I assume didSet{} and Combine @Published .sink{} are doing things interchangeably. So I want to ask what are the differences between them? And in my own opinion, didSet{} can do most of jobs Combine do. So why should Apple announce Combine framework?
Any help is appreciated.
class InfoViewModel: ObservableObject {
@Published var song: Song? {
didSet { // Here's the didSet{}: [1] load song data
if let song = song {
load(song: song)
}
}
}
private var songSelectedSubscription: AnyCancellable?
@Published var isInfoViewShown: Bool = false
init() { // Here's the Combine @Published .sink{}: [2] show the view
songSelectedSubscription = $song.sink{ self.isInfoViewShown = ($0 == nil ? false : true) }
}
}