Initialize Struct with Array

So I have a struct:

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

And an array of strings:

let myStrings = [ "Apple", "Banana", "Carrot" ]

I want to initialize an array of MyStructs with this array of strings, and then false for the selected property. For instance:

var structArray: [MyStruct]?

for string in myStrings {
    let myObject = MyStruct(title: string, selected: false)
    structArray.append(myObject)
}

Is there a better way to do this? I was thinking of trying to use map or filter but I’m not sure if this is the right direction to go. Thanks!

map is the way to go! Have you tried it yet?

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
var myStrings: [String]?
myStrings = [String]()

If you’re just going to initialize it as a non-optional array, why declare it as optional in the first place?

You could just do

var myStrings = [String]()

That would also remove the guard let later on :slight_smile:

ALSO

If they’re all going to start off as false, i would suggest creating an initializer with a default value:

init(title: String) {
    self.title = title
    selected = false
}

...

{ MyStruct(title: $0) }

OR just set the value in the declaration:

let selected = false

That way you don’t need to initialize it separately every time.

I’ve also created a list of other common swift mistakes (and how to fix them) here:
www.mypersonalcompass.com/swift-mistakes

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
    }
}

At that point wouldn’t it be easier to make it a class? That way you don’t need a fancy setter with the mutating keyword.

This topic was automatically closed after 166 days. New replies are no longer allowed.