I found this obscure problem when creating generic function inside Array extension. Let's say I have User class that I'll use to create array:
class User : NSObject {
let name : String
let surname : String
init(name : String, surname : String) {
self.name = name
self.surname = surname
}
override var description : String {
return self.name + " " + self.surname
}
}
Note that I need it to be subclass of NSObject. Now let's create two users and add them to array of users.
var user1 = User(name: "Jimmy", surname: "Page")
var user2 = User(name: "David", surname: "Guilmour")
var users = Array<User>()
users.append(user1)
users.append(user2)
Now I need an Array extension with function specific to Array, or any other subclass of User, that will add some test users to any array of users. Reason I write it inside extension and not my own type is because i want to check it's type using if let something = something as [User]
. If I build my own type I would not be able to do that.
extension Array {
mutating func addTestUsers<T : User>() {
var testUser1 = User(name: "King", surname: "Brown")
var testUser2 = User(name: "Carlos", surname: "Santana")
self.append(testUser1)
self.append(testUser2)
}
}
The problem comes when using append function or any other function that can somehow mutate the initial Array.
Error : Cannot invoke append with argument list of type (User)
I know it's because extension is never specified as extension of Array of User, but as I can see there is no way I can do this.