Swift使用可选的存储属性初始化Struct [英] Swift Initialize Struct with optional stored properties

查看:119
本文介绍了Swift使用可选的存储属性初始化Struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个Swift新手,我正试图使用​​带有可选属性的Structs。我已经做了很多搜索并得到了一些有效的东西,但感觉非常低效,所以想知道是否有更好/更易于管理的方式来实现我的目标。

I'm a Swift newbie and I'm trying to get my head around using Structs with optional properties. I've done quite a bit of searching and got something that works but it feels incredibly inefficient so wondered if there's a better/more manageable way of achieving my goal.

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

I'd like to use Structs to represent a business but I have no idea in advance which combination of properties any specific business is likely to have. This seems to mean that I have to create an init() for every possible combination of parameters.

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

Here's a simplified example (I have many more properties):

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
    }
}

然后我可以初始化课程像这样:

I can then initialise the class like this:

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

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

是吗?没有办法创建某种init(),其中参数是可选的?如果你可以指向我的术语或概念的方向来搜索那将是伟大的。

Is there no way to create some kind of init() where the parameters are optional? If you could point me in the direction of terms or concepts to search for that would be great.

推荐答案

使用默认值:

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

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

Then you can call the init like this:

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

这篇关于Swift使用可选的存储属性初始化Struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆