TL;DR
您在该类型的描述中看到了"未知上下文",因为它是在函数中定义的.您可以通过将这些类型定义移到函数外部或实现您自己的CustomStringConvertible
一致性来解决这个问题.
这是在哪里定义类型的问题.
请考虑:
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
struct WordDictionary: Codable {
var word: String
var usage: [Usage]
}
struct Usage: Codable {
var partOfSpeech: String
}
do {
let url = Bundle.main.url(forResource: "test", withExtension: "json")!
let data = try Data(contentsOf: url)
let words = try JSONDecoder().decode([WordDictionary].self, from: data)
print(words[0].usage)
} catch {
print(error)
}
return true
}
...
}
这会产生以下结果:
[MyApp.AppDelegate.($102bac454处的未知上下文).($102bac58c处的未知上下文).Usage(partOfSpeech:"Definer")]
这就是说,Usage
是在MyApp
内的AppDelegate
内的某个未知的上下文中定义的.简而言之,它不知道如何表示函数中定义的类型的层次 struct .
与此形成对比的是:
class AppDelegate: UIResponder, UIApplicationDelegate {
struct WordDictionary: Codable {
var word: String
var usage: [Usage]
}
struct Usage: Codable {
var partOfSpeech: String
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
let url = Bundle.main.url(forResource: "test", withExtension: "json")!
let data = try Data(contentsOf: url)
let words = try JSONDecoder().decode([WordDictionary].self, from: data)
print(words[0].usage)
} catch {
print(error)
}
return true
}
...
}
这将产生:
[MyApp.AppDelegate.Usage(partOfSpeech:"Definer")]
您还可以添加您自己的CustomStringConvertible
一致性:
struct WordDictionary: Codable {
var word: String
var usage: [Usage]
}
struct Usage: Codable {
var partOfSpeech: String
}
extension Usage: CustomStringConvertible {
var description: String { "Usage(partOfSpeech: \"\(partOfSpeech)\")" }
}
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
let url = Bundle.main.url(forResource: "test", withExtension: "json")!
let data = try Data(contentsOf: url)
let words = try JSONDecoder().decode([WordDictionary].self, from: data)
print(words[0].usage)
} catch {
print(error)
}
return true
}
...
}
这将产生:
[用法(partOfSpeech:"Definer")]
通过CustomStringConvertible
,您可以随心所欲地设置print
格式.