swiftuitableviewuicollectionviewios13uitableviewdiffabledatasource

UITableView And Diffable Data Source when supporting iOS 12 and 13


I have implemented UITableView Diffable Datasource in my project. It's working fine in IOS 13. When I run this application below iOS 13 Version then it gives me warning that it available on ios 13 only. so I am trying to implement UITableView for below iOS 13 version.

UITableView code is done but I am facing this issue on iOS 13.

@available(iOS 13.0, *)
typealias UserDataSource = UITableViewDiffableDataSource<TblSection, YoutubeVideoModel>
@available(iOS 13.0, *)
typealias UserSnapshot = NSDiffableDataSourceSnapshot<TblSection, YoutubeVideoModel>

here, I declare datasource variable

class SearchViewController: UIViewController {
    @available(iOS 13.0, *)
    var datasource: UserDataSource! //Stored properties cannot be marked potentially unavailable with '@available'
    }

Initialize Datasource and snapshot

 @available(iOS 13.0, *)
    func configureDatasource(){
         datasource = UITableViewDiffableDataSource<TblSection, YoutubeVideoModel>(tableView: searchTblView, cellProvider: { (tableView, indexPath, modelVideo) -> VideoTableViewCell? in
        self.configurationCell(indexPath: indexPath)
    })
    }

    @available(iOS 13.0, *)
    func createSnapshot(users: [YoutubeVideoModel]){
    var snapshot = UserSnapshot()
    snapshot.appendSections([.first])
    snapshot.appendItems(users)
    datasource.apply(snapshot, animatingDifferences: true)
      } 

I am facing this error when I declare Datasource please help thank you.

//Stored properties cannot be marked potentially unavailable with '@available'

I am facing same issue on collectionview too.


Solution

  • We can use @available on computed properties. However, lazy variables are considered computed properties and so you can use @available on them too. This has the nice benefit of removing the boilerplate of the extra stored property and the forced casts - in fact, it leaves no evidence of the property in your pre-iOS 10 code.

    You can simply declare it like this:

    @available(iOS 13.0, *)
    lazy var datasource = UserDataSource()
    

    You can check this gist for more informations https://gist.github.com/YogeshPateliOS/b2b13bfe5f7eef5cd7fa4a894cd35d5a