我在创建一个结构上有问题。
我的结构:
public struct Device: Codable {
let data: DeviceData
let meta: Meta?
}
public struct DeviceData: Codable {
let deviceID: String?
let type: String?
let attributes: Attributes?
private enum CodingKeys: String, CodingKey {
case deviceID = "id"
case type
case attributes
}
}
public struct Attributes: Codable {
let name: String?
let asdf: String?
let payload: Payload?
}
public struct Payload: Codable {
let example: String?
}
public struct Meta: Codable {
let currentPage: Int?
let nextPage: Int?
let deviceID: [String]?
}当我现在要创建这个结构的一个元素时,我想:
var exampleData = Device(
data: DeviceData(
type: "messages",
attributes: Attributes(
name: "Hello World",
asdf: "This is my message",
payload: Payload(
example: "World"
)
)
),
meta: Meta(
deviceID: ["asfd-asdf-asdf-asdf-asdfcasdf"]
)
)我会弄错的。无法详细指定此错误,因为当我删除"meta“元素时,因为它是可选的,因此发生了另一个错误.此特定代码的错误消息是:
呼叫中的额外参数“元”
我希望有人能帮我。
发布于 2018-06-25 15:23:35
您忘记了调用DeviceData.init(deviceID:type:attributes:)的DeviceData.init(deviceID:type:attributes:)命名参数,也忘记了currentPage和nextPage命名的Meta.init(currentPage:nextPage:deviceID)参数。
下面是一个编译的示例:
var exampleData = Device(
data: DeviceData(
deviceID: "someID",
type: "messages",
attributes: Attributes(
name: "Hello World",
asdf: "This is my message",
payload: Payload(
example: "World"
)
)
),
meta: Meta(
currentPage: 123,
nextPage: 456,
deviceID: ["asfd-asdf-asdf-asdf-asdfcasdf"]
)
)发布于 2018-06-25 16:41:52
您省略了DeviceData和Meta初始化器的参数。在对另一个回答的评论中,你问:
我是否必须添加它们并将其设置为零,即使它们是可选的?也许这就是我的问题!
你可以这样做,例如:
meta: Meta(currentPage: nil,
nextPage: nil,
deviceID: ["asfd-asdf-asdf-asdf-asdfcasdf"]
)或者,您可以编写自己的初始化程序,而不是依赖默认的成员级初始化程序,并在那里提供默认值,而不是在每次调用时提供默认值,例如:
init(currentPage : Int? = nil, nextPage : Int? = nil, deviceID : [String]? = nil)
{
self.currentPage = currentPage
self.nextPage = nextPage
self.deviceID = deviceID
}您最初的调用(省略了currentPage和nextPage )将是有效的,并将这两个调用设置为nil。
HTH
https://stackoverflow.com/questions/51026854
复制相似问题