如何修复 Swift 5.1 中的“使用未声明类型”错误?

Ami*_*Nie 4 swift swiftui

我是 Swift 和 iOS 开发的新手,并尝试按照官方 SwiftUI 教程进行学习。我在第 5 节中遇到错误(https://developer.apple.com/tutorials/swiftui/handling-user-input)。我仔细地遵循了每一步,在我完成了第 5 节的第 1 步之后,Xcode 弹出一个错误“使用未声明的类型‘UserData’”。我试图忽略并跟进。然而,我的 LandmarkList、LandmarkDetail、SceneDelegate 文件警告我同样的错误。我什至检查了从教程页面下载的项目的完整版本。除了我没有做的部分外,它们看起来完全一样。这里有没有人和我有类似的经历,或者你能提供一些建议吗?谢谢!

我正在使用 Xcode 11 和 Swift 5。

这是我在 Models 文件夹下创建的 UserData 类。

import Combine
import SwiftUI

final class UserData: ObservableObject {
    @Published var showFavoritesOnly = false
    @Published var landmarks = landmarkData
}
Run Code Online (Sandbox Code Playgroud)

这是不断提示错误的rootview文件。

import SwiftUI

struct LandmarkList: View {
    @EnvironmentObject private var userData: UserData  // Use of undeclared type 'UserData'

    var body: some View {
        NavigationView {
            List { // Unable to infer complex closure return type; add explicit type to disambiguate
                Toggle(isOn: $userData.showFavoritesOnly){ // Use of unresolved identifier '$userData'
                    Text("Favorites Only")
                }

                ForEach(userData.landmarks) { landmark in
                    if !self.userData.showFavoritesOnly || landmark.isFavorite {
                        NavigationLink(destination: LandmarkDetail(landmark: landmark)
                            .environmentObject(self.userData)) {
                            LandmarkRow(landmark: landmark)
                        }
                    }
                }
            }
            .navigationBarTitle(Text("Landmarks"))
        }
    }
}

struct LandmarkList_Previews: PreviewProvider {
    static var previews: some View {
        ForEach(["iPhone SE", "iPhone XS Max"], id: \.self) { deviceName in
            LandmarkList()
                .previewDevice(PreviewDevice(rawValue: deviceName))
                .previewDisplayName(deviceName)
        }
        .environmentObject(UserData()) // Use of unresolved identifier 'UserData'
    }
}
Run Code Online (Sandbox Code Playgroud)

Evg*_*niy 8

您需要清理并关闭 Xcode,然后删除派生数据,然后重新打开 Xcode。我在做苹果教程时一直遇到这个问题。

  • 太感谢了!!!!你神奇简单的答案让我摆脱了困扰我两天的难题!我应该在我被困住的那一刻就问。再次,我想再次感谢您! (2认同)