Home > database >  How to create optional parameters on Swift struct
How to create optional parameters on Swift struct

Time:04-06

I am attempting to build a struct for an input filed that has optional icons.

If an icon name is passed in as a param then it will load, else it will not.

I am getting the error Value of optional type 'String?' must be unwrapped to refer to member 'isEmpty' of wrapped base type 'String' which I do not understand.

Also, when I initialize the struct it is still requiring the params despite the optional ? indicator. enter image description here

CodePudding user response:

Change the if statement to this

if preIcon?.isEmpty == false

Then change

var preIcon: String?

var postIcon: String?

CodePudding user response:

Since preIcon is an optional, you have to unwrap it before you can access properties on it. So, your line will need to be:

if let preIcon = preIcon, !preIcon.isEmpty {

You can learn more about optional binding (the if let syntax used above) at: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html


In terms of the struct requiring properties marked as optionals, although Xcode may include the optional properties in autocomplete, it doesn't actually require that you include values for them -- they can be deleted an your initializer will still work.

  • Related