简体   繁体   English

如何在 swift 中定义和使用具有可选属性的结构?

[英]How to define and use a struct with an optional property in swift?

I want to have a model "places" that has a optional.我想有一个可选的 model “地方”。

struct PlaceObj: Identifiable {
let id = UUID()
let name: String
let image: UIImage
}

Not every PlaceItem may have an image, so I wanted to keep it optional.不是每个 PlaceItem 都可能有图像,所以我想保持它是可选的。 I would like to use it like:我想像这样使用它:

PlaceObj(
name: "Place1"
)

But that gives me an error that image is not defined, this means I have to do:但这给了我一个错误,即图像未定义,这意味着我必须这样做:

PlaceObj(
name: "Place1",
image: nil
)

But I can't do nil unless I put a questionmark after UIImage.但是除非我在 UIImage 后面加上一个问号,否则我不能做 nil。 Is there a best practice/preferred way to handle this?是否有最佳实践/首选方法来处理此问题? Is there no way to just omit "image:nil" from every instantiation when trying to use it?尝试使用它时,有没有办法从每个实例中省略“image:nil”?

Give it a default value of nil , and that compiler-generated default memberwise initializer will have defaulted parameters to match, thanks to SE-0242 – Synthesize default values for the memberwise initializer :给它一个默认值nil ,编译器生成的默认成员初始化器将具有默认参数来匹配,这要归功于SE-0242 - 为成员初始化器合成默认值

struct PlaceObj: Identifiable {
    let id = UUID()
    let name: String
    var image: UIImage? = nil
}

The compiler-provided initializer will behave as if you wrote:编译器提供的初始化程序的行为就像您编写的那样:

init(name: String, image: UIImage? = nil) {
    self.name = name
    self.image = image
}

You can declare your own initializer:您可以声明自己的初始化程序:

struct PlaceObj: Identifiable {
    let id = UUID()
    let name: String
    let image: UIImage?
    
    init(name: String) {
        self.name = name
        self.image = nil
    }
}

Then: let b = PlaceObj(name: "Bob")然后: let b = PlaceObj(name: "Bob")

or (thanks to @Alexander's comment):或(感谢@Alexander 的评论):

struct PlaceObj: Identifiable {
    let id = UUID()
    let name: String
    var image: UIImage? = nil
}

which avoids having to make an initializer, but keep in mind it is only available in Swift 5.1+这避免了必须进行初始化,但请记住它仅在 Swift 5.1+ 中可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM