I am trying insert a value in an Array at alternate position, And its work fine. Now I want to Insert value at 0 index first and than same way as I have.
Code snippet-
var list = ["A","B","C","D"]
self.isAdLoaded = "true"
self.listData = Array(self.list.map { [$0] }.joined(separator: [self.isAdLoaded]))
Output Is-
["A","true","B","true","C","true","D"]
But I want true at 0 Index like below-
["true","A","true","B","true","C","true","D"]
CodePudding user response:
I believe you could do this with flatMap like…
let list = [“a”, “b”, “c”]
let other = list.flatMap { [“true”, $0] }
This will return an array of “true” and the value. And then the flat map will flatten the array of arrays into an array of strings again.
Having said that… I feel like you would do much better by creating structs for your data and storing it that way. It feels very much like you’re doing something wrong with this question.
If you had a struct like…
struct Thing {
let name: String
var adLoaded: Bool = true
}
Then you could do something like…
let data = list.map(Thing.init)
And you would have your array of structs with all the booleans set to true.
CodePudding user response:
Just prepend the element at the array
self.listData = [self.isAdLoaded] Array(self.list.map { [$0] }.joined(separator: [self.isAdLoaded]))