Rolando
Rolando

Reputation: 62596

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

I want to have a model "places" that has a optional.

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. 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. 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?

Upvotes: 3

Views: 3855

Answers (2)

Alexander
Alexander

Reputation: 63167

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:

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
}

Upvotes: 7

jnpdx
jnpdx

Reputation: 52347

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")

or (thanks to @Alexander's comment):

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+

Upvotes: 1

Related Questions