Assign To
July 23, 2020
My dad taught Philosophy for many years at Oberlin College.
I remember how carefully he prepared for class. It's one of my many strong memories of him when I was young.
I'd come in to the living room and he'd be sitting in his chair reading Plato, making notes.
He'd taught this text every year. The text hadn't changed. And yet, every time he would reteach it, he would reread it.
A two thousand year old text.
"Why," I would ask. "What could possibly have changed since the last time you read it?"
"I always see something new," he would say. "I always see something a different way."
And so, before I teach, I look at the material one more time. And often I find myself not being happy with the way I presented it last time. Maybe this receive(on:) should move over here.
Indeed, that was one of the changes I made this afternoon as I went over my First Steps in Combine class one more time.
It's kind of silly. I just rewrote it last week. But then today I wrote it once again.
There were very few changes to the Combine framework at this year's WWDC, but one of the ones I embraced immediately was assign(to:).
There was an assign(to: on:) introduced last year. But it had some issues. It strongly retained the root (often self) and you had to hold on to the Cancellable that you got back or the subscription would disappear.
So assign(to:) is much cleaner if you are assigning to a Publisher. This makes a lot of SwiftUI code nicer.
My current sample code grabs the information from one place and passes it on the the view like this.
player.imageName.assign(to: &$playerImageName)
Thank goodness I checked my code today. Xcode 12 Beta 3 introduced the &. Until today the call was
assign(to: $playerImageName)
And before assign(to:) the call was
assign(to: \.playerImageName, on: self)
or if you wanted to avoid the memory leak
sink {[weak self] string in
self?.playerImageName = string
}
I don't know how I feel about the new &. It feels clunky. On the other hand, I like the new assign() better than the alternatives so I'll live with it.