Search code examples
iosuicollectionviewrx-swift

Why I cannot use model<T>(at indexPath: IndexPath) method of Reactive<UICollectionView> type?


I want to get the dataModel of UICollectionView at specific indexPath, I noticed that there is a method called model<T>(at indexPath: IndexPath), and I think that's what I need, but the compiler complains about like this

enter image description here

I also noticed that RxSwift has provided other instance methods like modelSelected<T>(_ modelType: T.Type) and I can use it with no error like the picture, I think they are the same type(both are instance method), but I get different results, is there something I missed when using this method? I would be happy if somebody can give some advice.


Solution

  • The model(at:) method returns a generic type. You have not given the compiler enough information to infer the generic type and that has caused the compiler to assume you are trying to do something completely different. Also, remember that the call can throw. Do this instead:

    let myThing: MyThing? = try? collectionView.rx.model(at: indexPath)
    

    or you can do:

    let myThing = try? collectionView.rx.model(at: indexPath) as MyThing
    

    The modelSelected(_:) method works because the type of T is specified as a parameter so the compiler is able to figure it out.