访问数组并从另一个ViewController对其进行排序

时间:2017-02-09 14:48:06

标签: ios swift delegates protocols

想象一下,我有一个包含一些值的数组:

let countryName = ["USA", "Canada", "Italy", "Israel"]

当点击按钮时,它开始按区域对此数组进行排序:

let countryToRegionDic = [
    "United States" : "America",
    "Czech Republic" : "Europe",
]

func useFilter() {
    self.countryName.forEach({ (country) in

        let countryRegion = self.countryToRegionDic[country]

        if (countryRegion != nil && europeFilter.contains(countryRegion!)){

            self.filtered.append(country)
            self.countryName = self.filtered.removeDuplicates()
            self.tableView.reloadData()
        }           
    })
}

我希望它在另一个" FiltersViewController"中使用这个排序功能。 ,因为过滤的价值来自于这个" FiltersViewController"。认为我需要使用代表或协议,但不知道如何以及在何处。谢谢!

1 个答案:

答案 0 :(得分:0)

关于委托模式的一个小例子......

public protocol CountrySort: class
{
    func sorted(_ array: [String]) -> Void
}

public class ControllerA
{
    public var countryName: [String]!

    public weak var delegate: CountrySort?

    public func userFilter() -> Void
    {
        // Do something here...
        countryName.sort()

        self.delegate?.sorted(countryName)
    }
}

public class ControllerB
{
    public init()
    {
        // Call the other UIViewController
        let controllerA: ControllerA = ControllerA()
        controllerA.countryName = ["USA", "Canada", "Italy", "Israel"]

    }
}

extension ControllerB: CountrySort
{
    public func sorted(_ array: [String]) -> Void
    {
        print("And now the other controller sort the array")

        for item in array
        {
            print("\t\(item)")
        }
    }
}