我正在尝试从捆绑包中的json文件中读取数据,并且要实现这一点,我创建了一个protocol ReadableJSONFile
,它具有fileName
来存储json文件名和readFromJSONFile()
解码文件
public protocol ReadableJSONFile {
/// The name of your json file in the bundle
var fileName: String { get }
func readFromJSONFile() -> Self
}
和
public extension ReadableJSONFile where Self: Codable {
var fileName: String {
return "\(String(describing: Self.self)).json"
}
func readFromJSONFile() -> Self {
guard let url = Bundle.main.url(forResource: fileName, withExtension: nil) else {
fatalError("Failed to locate \(fileName) in app bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(fileName) in app bundle.")
}
let decoder = JSONDecoder()
guard let loaded = try? decoder.decode(Self.self, from: data) else {
fatalError("Failed to decode \(fileName) from app bundle.")
}
return loaded
}
}
我编写了这个简单的json文件,并将其命名为ModelA.json
{
"color": "yellow",
"name": "Mike"
}
然后创建此模型来表示ModelA.json
文件
struct ModelA: Codable, ReadableJSONFile {
let color: String
let name: String
}
在我的视图控制器中,我有以下代码行
class ViewController: UIViewController {
let data = ModelA.readFromJSONFile() // Here an error saying "Instance member 'readFromJSONFile' cannot be used on type 'ModelA'; did you mean to use a value of this type instead?"
override func viewDidLoad() {
super.viewDidLoad()
print(data.name)
}
}
当我将fileName
和readFromJSONFile()
设为static
时,一切正常,但是当我这样做时,我无法覆盖fileName
内部的ModelA
确认为ReadableJSONFile
答案 0 :(得分:0)
您无法访问不是类型成员的类成员,而您需要像我在下面创建的那样创建类的对象(实例),
class ViewController: UIViewController {
let instance = ModelA()
let data = instance.readFromJSONFile()
override func viewDidLoad() {
super.viewDidLoad()
print(data.name)
}
}