首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift 4:结构中的结构

Swift 4:结构中的结构
EN

Stack Overflow用户
提问于 2018-06-25 15:18:55
回答 2查看 433关注 0票数 1

我在创建一个结构上有问题。

我的结构:

代码语言:javascript
复制
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]?
}

当我现在要创建这个结构的一个元素时,我想:

代码语言:javascript
复制
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“元素时,因为它是可选的,因此发生了另一个错误.此特定代码的错误消息是:

呼叫中的额外参数“元”

我希望有人能帮我。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-25 15:23:35

您忘记了调用DeviceData.init(deviceID:type:attributes:)DeviceData.init(deviceID:type:attributes:)命名参数,也忘记了currentPagenextPage命名的Meta.init(currentPage:nextPage:deviceID)参数。

下面是一个编译的示例:

代码语言:javascript
复制
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"]
    )
)
票数 2
EN

Stack Overflow用户

发布于 2018-06-25 16:41:52

您省略了DeviceDataMeta初始化器的参数。在对另一个回答的评论中,你问:

我是否必须添加它们并将其设置为零,即使它们是可选的?也许这就是我的问题!

你可以这样做,例如:

代码语言:javascript
复制
meta: Meta(currentPage: nil,
           nextPage: nil,
           deviceID: ["asfd-asdf-asdf-asdf-asdfcasdf"]
          )

或者,您可以编写自己的初始化程序,而不是依赖默认的成员级初始化程序,并在那里提供默认值,而不是在每次调用时提供默认值,例如:

代码语言:javascript
复制
init(currentPage : Int? = nil, nextPage : Int? = nil, deviceID : [String]? = nil)
{
   self.currentPage = currentPage
   self.nextPage = nextPage
   self.deviceID = deviceID
}

您最初的调用(省略了currentPagenextPage )将是有效的,并将这两个调用设置为nil

HTH

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51026854

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档