'How to create optional parameters on Swift struct

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



Solution 1:[1]

Change the if statement to this

if preIcon?.isEmpty == false

Then change

var preIcon: String?

var postIcon: String?

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jnpdx