Marduk
Marduk

Reputation: 129

Cannot find type 'T' in scope Swift

I state that it is a few years that I have not programmed in Swift, some time ago I had created this extension to randomly access the elements of an array but I get the error "Cannot find type 'T' in scope"

extension Array {
    func randomElement() -> T {
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

How could I solve? I also tried to put Array in it but I always get the same error

Upvotes: 4

Views: 6476

Answers (1)

Shadowrun
Shadowrun

Reputation: 3867

The generic on Array is spelled Element not T

You can see that if you jump to the definition of Array:

@frozen public struct Array<Element> {

So your function needs to return an Element not a T

Upvotes: 5

Related Questions