【问题标题】:Cannot find 'LocationsData' in scope在范围内找不到“LocationsData”
【发布时间】:2020-09-08 20:54:24
【问题描述】:

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)!
}
} 

【问题讨论】:

  • LocationsData 没有在任何地方声明。你的意思是locationsDataTypes

标签: json parsing swiftui


【解决方案1】:

正如 pawello2222 所暗示的,locationsData 没有在任何地方声明。

我怀疑你的 List 视图构建器函数写错了。

而不是这个...

List(LocationsData, id: \.id) { locationsDataTypes in

试试下面...

List(locationsDataTypes, id: \.id) { locationsData in
    ...
                Image(locationsData.imageName)
                    .resizable
    ...
}

其中locationsDataTypes 是集合,在您的情况下,LocationsDataTypeslocationsData 的数组是通过该集合的每次迭代的单个实例。

此外,在堆栈溢出中编写问题时,最佳做法是将相关代码包含在代码块中在您的问题中,而不是通过超链接访问。这有很多原因,这里有几个......

  • 作为响应的一部分,SO 社区可以更轻松地将您的代码复制并粘贴到他们的解决方案中,从而为我们节省了大量时间;
  • 链接断开,让未来可能遇到同样问题的任何人都无法了解您的问题。

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 2021-06-18
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多