一尘不染

带有可选存储属性的Swift Initialize Struct

swift

我是一名Swift新手,我正在努力使Structs具有可选属性。我已经做了很多搜索,找到了可以解决的问题,但是效率低下,所以想知道是否有更好/更易管理的方法来实现我的目标。

我想使用Structs来代表一家企业,但我事先不知道任何特定企业可能具有哪种属性组合。这似乎意味着我必须为每种可能的参数组合创建一个init()。

这是一个简化的示例(我还有更多属性):

import Foundation

struct Business {
    let name : String
    var web : String?
    var address: String?

    // just the business name
    init(busName: String) {
        self.name = busName
    }

    // business name + website
    init(busName: String, website: String) {
        self.name = busName
        self.web = website
    }

    // business name + address
    init(busName: String, address: String) {
        self.name = busName
        self.address = address
    }

    // business name + website + address
    init(busName: String, website: String, address: String) {
        self.name = busName
        self.web = website
        self.address = address
    }
}

然后,我可以像这样初始化类:

Business(busName: "Dave's Cafe", website: "http://www.davescafe.com")

Business(busName: "Sarah's Brewhouse", address: "41 Acacia Ave, Smalltown")

没有办法在参数为可选的情况下创建某种init()吗?如果您能指出我要搜索的术语或概念的方向,那将很好。


阅读 224

收藏
2020-07-07

共1个答案

一尘不染

使用默认值:

init(busName: String, website: String? = nil, address: String? = nil) {
    self.name = busName
    self.web = website
    self.address = address
}

然后您可以像这样调用init:

_ = Business(busName: "Foo")
_ = Business(busName: "Foo", website: "www.foo.bar")
_ = Business(busName: "Foo", address: "bar")
_ = Business(busName: "Foo", website: "www.foo.bar", address: "bar")
2020-07-07