当 SwiftUI 已经导入了它时,为什么我需要导入它? [英] Why do I need to import Combine when SwiftUI already imports it?

查看:46
本文介绍了当 SwiftUI 已经导入了它时,为什么我需要导入它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试聆听 @State 的变化并遵循

一旦我将 import Combine 添加到我的代码中,它就会编译.但这不应该是多余和不必要的吗?

解决方案

仅仅因为您从某个框架/库(模块 A)导入并不自动意味着您可以访问模块 A 导入的所有类型(模块 B, C, D) 在您导入的文件中只是 A.

一个完美的例子就是你正在经历的,其中 SwiftUI 导入 Combine,但你不能在你的代码中使用 Just无需显式导入 Combine 自己.

然而,这并非所有时间.例如,CGFloat 是在 CoreGraphics 中定义的,但如果你导入 SwiftUI,你就可以访问它.如果您只导入 Foundation,您无权访问它.当然,这不是一个完美的例子,因为您的问题引用了两个 Swift 框架,而 CoreGraphics 和 Foundation 来自 Objective-C 世界.

为了让您不必导入Combine,SwiftUI 框架必须为您导出Combine.这可以使用 @_export 来完成:

因为这还没有完成,所以当你想使用它的类型时,你被困在导入 Combine ,就像如果你想使用你必须导入 CoreDataCoreData 类型,尽管像 Combine 一样,它是由 SwiftUI 导入(但不导出).

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"

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

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

解决方案

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.

这篇关于当 SwiftUI 已经导入了它时,为什么我需要导入它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆