1

I have an array of string which has x amount of elements and x >= 2

let arrayOfString = ["A", "B"]
// or
let arrayOfString = ["A", "B", "C", ...]

and I want to use the arrayOfString to create an object array in this format

[
    {
        "option": "A"
    },
    {
        "option": "B"
    },
    ...
] 

I have tried to create a struct like this

    struct PollOptionArray {
    let option: String
}

and loop through the string array

var pollDetailArray = [PollOptionArray]()

      for index in arrayOfString {
             pollDetailArray.append(PollOptionArray(option: index)
       }

but I think it is wrong Can anyone give me a suggestion? Thank you

0

1 Answer 1

2

A simple map will work:

let objectArray = arrayOfString.map { [ "option" : $0 ] }

Or, based on your struct:

let pollDetailArray = arrayOfString.map { PollOptionArray(option: $0) }
Sign up to request clarification or add additional context in comments.

4 Comments

What do you think about my method?
I just updated based on your struct (which wasn't in the question when I first answered). Your code works just fine if you want to create an array of struct. The map in my answer gives the same result.
Oh cool. Lastly, is there a way that I can ignore empty string because in my string array, sometimes it is ["A", "", "B"] and I want to ignore that empty string. Thanks!
Filter the array: let pollDetailArray = arrayOfString.filter { !$0.isEmpty }.map { PollOptionArray(option: $0) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.