-1

I have an array of list objects [UsersList]. I wish to append an indicator into the [UserList] on every 60th index. So the outcome I would like to have is something like below:[user1,...user60,"Yes",user61,user62]

Can someone help me on how to append on this outcome and how do I loop it to display it?

Thanks

Kuldeep
  • 4,466
  • 8
  • 32
  • 59
kamenr
  • 95
  • 1
  • 13

3 Answers3

0

Something like that could also work:

var i = 60
while (i < usersList.count) {
     usersList.insert("yes", at: i)
     i += 60
}
RomOne
  • 2,065
  • 17
  • 29
  • what if I need to add in to 120th 180th and so on? I need the indicator to be there in every 60th increment index – kamenr Apr 18 '18 at 04:05
  • Yeah that code is doing what you are asking. The while loop condition is stoping when your array is shorter than the index – RomOne Apr 18 '18 at 04:10
  • So it will keep adding your indicator until the end of you array. If you array is 119 long, it won’t add it. If it’s 240 long it will add it at the 60th, 120th, 180th and 240th position (btw I really recommend you to have a look to how while loops work ;) ) – RomOne Apr 18 '18 at 04:24
0

Maybe something like this, replace it with your array and change the number, then it will have.

var a: [Any] = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]
let by = 3
if by < a.count {
    for i in stride(from: by, to: a.count, by: by).reversed() {
        a.insert("z", at: i)
    }
}
//[1, 2, 3, "z", 4, 5, 6, "z", 7, 8, 9, "z", 8, 7, 6, "z", 5, 4, 3, "z", 2, 1]
Tj3n
  • 9,837
  • 2
  • 24
  • 35
  • how to get the elements from an [Any] array? because i need to display the based on the "z" flag, if its "z", display Z, if it's not, display the normal item – kamenr Apr 18 '18 at 06:54
  • [user1,...user60,"Yes",user61,user62] the is the sample of the [Any] array, how to loop it out and display into collectionview? – kamenr Apr 18 '18 at 07:05
  • You can cast the object from `Any` to `UsersList` or `String` with `if let` inside your loop, then do what you need with them – Tj3n Apr 18 '18 at 07:09
0

try to do like this:

update

let arr: NSMutableArray = []

var i = 1
var cnt = 0

while i < 200 {
    if i % 61 != 0 {
        arr.add(String.init(format: "user%d", i - cnt))
    } else {
        arr.add("YES")
        cnt += 1
    }
    i += 1
}
XM Zhang
  • 123
  • 1
  • 10