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!
The array myStrings is optional because in my actual code it is initialized via a network call, so there’s the chance it could be nil. I kept that out for this simple example.
I added the init function to MyStruct, thanks for that! It now looks like this:
struct MyStruct: Codable {
let title: String
var selected = true
init(title: String) {
self.title = title
}
mutating func setSelected(_ value: Bool) {
selected = value
}
}