想象一下,我有一个包含一些值的数组:
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"。认为我需要使用代表或协议,但不知道如何以及在何处。谢谢!
答案 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)")
}
}
}