My project contains the JSON file 'LocationsData.json'
An error is displayed 'Cannot find 'LocationsData' in scope'
((如果需要-以下代码包含在我的'Data.swift'文件中,这是'SearchRedirect.swift'中的var'locationsDataTypes'所引用的)
import UIKit
import SwiftUI
import CoreLocation
let locationsDataTypes: [LocationsDataTypes] = load("LocationsData.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
final class ImageStore {
typealias _ImageDictionary = [String: CGImage]
fileprivate var images: _ImageDictionary = [:]
fileprivate static var scale = 2
static var shared = ImageStore()
func image(name: String) -> Image {
let index = _guaranteeImage(name: name)
return Image(images.values[index], scale: CGFloat(ImageStore.scale), label: Text(name))
}
static func loadImage(name: String) -> CGImage {
guard
let url = Bundle.main.url(forResource: name, withExtension: "jpg"),
let imageSource = CGImageSourceCreateWithURL(url as NSURL, nil),
let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)
else {
fatalError("Couldn't load image \(name).jpg from main bundle.")
}
return image
}
fileprivate func _guaranteeImage(name: String) -> _ImageDictionary.Index {
if let index = images.index(forKey: name) { return index }
images[name] = ImageStore.loadImage(name: name)
return images.index(forKey: name)!
}
}
答案 0 :(得分:0)
正如pawello2222所暗示的,locationsData
并未在任何地方声明。
我怀疑您的List
视图构建器函数编写不正确。
代替这个...
List(LocationsData, id: \.id) { locationsDataTypes in
尝试以下操作...
List(locationsDataTypes, id: \.id) { locationsData in
...
Image(locationsData.imageName)
.resizable
...
}
locationsDataTypes
是集合,在您的情况下,LocationsDataTypes
和locationsData
的数组是该集合中每次迭代的单个实例。
此外,在堆栈溢出中编写问题时,最佳实践是将相关代码包含在问题中的代码块 中,而不是通过超链接访问。造成这种情况的原因很多,这里有几个...