Initialize Struct with Array

Thanks for that insight! Here is what I ended up with:

struct MyStruct {
    let title: String
    let selected: Bool
}

var myStrings: [String]?

...

// simple version of initializing optional string array
myStrings = [String]()
myStrings?.append("Apple")
myStrings?.append("Banana")
myStrings?.append("Carrot")


guard let mStrings = myStrings else { return }
let structArray = mStrings.map { MyStruct(title: $0, selected: false) }

The thing I think was I missing was the fact that my original string array is an optional, so I added the guard statement before mapping and now it works! Thanks for the help!

1 Like