如何从 Swift 中的另一个 class/file 访问数组

How to access an array from another class/file in Swift

在 swift 中遇到此问题。我在“Products.swift”class 中有一个“产品”数组。当我尝试将“产品”数组访问到“SortLauncher.swift”class 时 它的 returns “无” 这是我的代码

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)
}}

响应:无法排序。

您必须传递父对象(Products) class,或者您必须在 SortLauncher class 中声明一个对象来保存 Products class 对象的引用以访问数据.我只是创建了演示来访问 SortLauncher class 中产品 class 的所有变量。 导入基金会 导入 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)