我有这个结构,如果我运行这个代码,我会得到nil。我在另一个结构中使用了一个结构。接下来,我设置了第一个变量,并将值放入另一个变量中。参见下面的代码
struct Main: codable{
let name: String?
let url: [SiteUrl]?
}
struct SiteUrl: codable{
let url: String?
}
struct People: codable{
let nickname: string?
let url: [SiteUrl]
}
var test :Main?
test.url.append(“test”)
var people: People?
people?.url = test.url
print(test)//result nil
这是因为
var test: Main?
是可选
在分配之前,您需要先实例化测试。
所以答案是
var test :Main?
var name: String = "name"
var url: [SiteUrl] = []
test = Main(name: name, url )
test.url.append(“test”)
var people: People?
people?.url = test.url
print(test)//result nil
或者,你可以只做下面更简单的
var test : Main? = Main(name: "name", [])
test.url.append(“test”)
var people: People?
people?.url = test.url
print(test)//result nil