ovo ovo - 1 month ago 23
Swift Question

Why doesn’t my Swift array extension work?

I am trying to run this code, and this error is being triggered

Cannot invoke 'append' with an argument list of type '(Int)'


What am I doing wrong?

extension Array {
mutating func random100() {
for _ in 0 ... 99 {
self.append(Int(arc4random() % 10)) // Cannot invoke 'append' with an argument list of type '(Int)'
}
}
}

Answer

You must constraint your extension to Int types :

extension RangeReplaceableCollection where Iterator.Element == Int {
    mutating func random100() {
        for _ in 1...100 {
            append(Int(arc4random_uniform(10)))
        }
    }
}

And as you cannot directly constraint Array, you must constraint the protocol where the append method is defined.

Then you can use it on any array of Int:

var myArray = [3,5,6]
myArray.random100()