4

Having trouble with this in swift. I have a “products" array in “Products.swift” class. When i try to access “products” array into “SortLauncher.swift” class its returns “nil” Here is my code

Products.swift

import Apollo
class Products: UICollectionViewController, UICollectionViewDelegateFlowLayout, UISearchResultsUpdating, UISearchBarDelegate {
   var products: [ProductsQuery.Data.Node.AsCollection.Product.Edge]? {
    didSet {
        filterPro = products
        collectionView?.reloadData()
    }
}
 var filterPro : [ProductsQuery.Data.Node.AsCollection.Product.Edge]? {
    didSet {
    }
}}

SortLauncher.swift

class SortLauncher: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

  var sortProducts = Products()

    if let sorted = sortProducts.products {
        print("Sorted Products \(sorted.count).")
    } else {
        print("Unable to sort.")
    }

    handleGesture()

}
override init() {
    super.init()
    sortingList.dataSource = self
    sortingList.delegate = self

    sortingList.register(SortListCell.self, forCellWithReuseIdentifier: cellId)
}}

Response : Unable to sort.

1 Answers1

1

You have to pass object of parent(Products) class, or you have to declare one object in SortLauncher class to hold the reference of Products class object to access data. i have simply created demo to access all the variable of products class in SortLauncher class. import Foundation import UIKit

class Products: NSObject
{
    var products: [String]?
    {
        didSet
        {
            filterPro = products
        }
    }
    var filterPro : [String]?
    {
        didSet
        {
        }
    }}

class SortLauncher: NSObject
{

    func sort(parent:Products)
    {

        if let sorted = parent.products
        {
            print("Sorted Products \(sorted.count).")
        } else {
            print("Unable to sort.")
        }



    }
    override init()
    {
            super.init()
    }
}
let productObject:Products = Products.init()
productObject.products = ["a","b","c","d"];

let sObject:SortLauncher = SortLauncher.init()
sObject.sort(parent: productObject)
Jaydeep Vyas
  • 4,411
  • 1
  • 18
  • 44