add same item multiple times to list in swift

To add the same item multiple times to a list (array) in Swift, you can use the Array class's append(contentsOf:) method.

  1. First create an empty list of the desired type:
main.swift
var myList: [Int] = []
23 chars
2 lines
  1. Use the append(contentsOf:) method to add multiple copies of an item to the list:
main.swift
let itemToAdd = 4
let numberOfTimesToAdd = 3
myList.append(contentsOf: Array(repeating: itemToAdd, count: numberOfTimesToAdd))
127 chars
4 lines

This will add the integer 4 three times to the myList array. The resulting array will be [4, 4, 4].

Note that the Array(repeating:count:) constructor simply creates an array with count number of copies of the specified element. The append(contentsOf:) method appends each element of the given sequence to the end of the array. In this case, the sequence is the array created by Array(repeating:count:), which contains multiple copies of the item to be added.

related categories

gistlibby LogSnag