tl;dr
您在类型的描述中看到“未知上下文”,因为它是在函数内部定义的。您可以通过将这些类型定义移到函数之外或实现您自己的来解决此问题CustomStringConvertible https://developer.apple.com/documentation/swift/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:“确定符”)]
也就是说Usage
是在某些未知的上下文中定义的AppDelegate
within MyApp
。简而言之,它不知道如何表示函数内定义的类型的层次结构。
对比一下:
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: "限定符")]
您也可以添加自己的CustomStringConvertible https://developer.apple.com/documentation/swift/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
}
...
}
其产生:
[用法(词性:“限定词”)]
Through CustomStringConvertible
,你可以使print
按照您想要的方式格式化它。