5

I'm trying to listen to @State changes and followed this answer. Here's my code:

import SwiftUI

struct ContentView: View {
    @State var isOn = false
    
    var body: some View {
        Toggle("Selection", isOn: $isOn)
            .onReceive(Just(isOn)) { isOn in
                print("Toggle is on? \(isOn)")
            }
    }
}

It doesn't compile: I get "Cannot find 'Just' in scope"

Cannot find 'Just' in scope with the line containing 'Just' highlighted

Just is part of the Combine framework. But, I thought SwiftUI already imported Combine? I Command-clicked import SwiftUI, then pressed Jump to Definition, and there it was at the top.

Jump to Definition import Combine is at the top
Jump to Definition in popup menu Line 1 of SwiftUI file is import Combine

Once I add import Combine to my code, it compiles. But shouldn't this be redundant and unnecessary?

Build succeeded

aheze
  • 24,434
  • 8
  • 68
  • 125

1 Answers1

8

Just because you import from a certain framework/library (module A) does not automatically mean you get access to all of the types that module A imports (module B, C, D) in your file where you've imported just A.

A perfect example of that is what you are experiencing, where SwiftUI imports Combine, but you can't use Just in your code without explicitly importing Combine yourself.

However, this isn't true all of the time. For example, CGFloat is defined in CoreGraphics, but you have access to it if you import SwiftUI. You don't have access to it, if you only import Foundation. Of course, this is not a perfect example since your question references two Swift frameworks, while CoreGraphics and Foundation come from the Objective-C world.

In order for you to not have to import Combine, the SwiftUI framework would have to export Combine for you. This can be done using @_export:

Since that has not been done, you're stuck importing Combine when you want to use its types, just as you have to import CoreData if you want to use CoreData types, even though, like Combine, it is imported (but not exported) by SwiftUI.

jnpdx
  • 45,847
  • 6
  • 64
  • 94