To add the same item multiple times to a list (array) in Swift, you can use the Array
class's append(contentsOf:)
method.
main.swift23 chars2 lines
append(contentsOf:)
method to add multiple copies of an item to the list:main.swift127 chars4 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.
gistlibby LogSnag