Reputation: 5345
The SwiftUI documentation is challenging to find out what is actually happening on each render / when they occur / what is causing them (or I don't know where to look!)
I'm trying to avoid building a separate class to do logic and referencing it from my views, I'm just not understanding where logic goes and the official tutorial doesn't go into it much. I'm attempting to build a component based system like React where children are independent and don't have to rely on a helper class.
To be clear, I think the answer is 1.
below.
Here is what I don't get.
In react I can say:
const [someStateVariable, setSomeStateVariable] = useState("")
const dependsOnStateVariable = someStateVariable ? 0 : 1;
But in SwiftUI I cannot do:
@State var someStateVariable: String = ""
var dependsOnSomeStateVariable = someStateVariable ? 0 : 1
The same goes for doing logic with props being passed in (initialization variables). In react, I can do things with those props. In Swift, I cannot.
Does all this logic have to go into init
? I guess from reading struct documentation that makes sense, I just want to make sure I understand it correctly.
Where is the documentation on the diffing algorithm and lifecycle events? What triggers a render? When is init
run? On each render (ie. the properties passed in change or the state changes) or the first time it appears (I'm guessing on each render since onAppear exists).
How do I respond to side effects? It appears it's a bit complex. Is there a useEffect equivalent? Code I can run only when certain state or input variables are changed?
Upvotes: 8
Views: 846
Reputation: 1241
You can make dependsOnSomeStateVariable
a computed property.
var dependsOnSomeStateVariable: Int {
someStateVariable ? 0 : 1
}
As far as I know the exact View
lifecycle is not documented (but some of it has been reverse engineered
For observed objects (@ObservedObject
) you can listen for published changes (objectWillChange
, usually in combination with DispatchQueue.main.async
).
Upvotes: 1