gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:41:53 25 4
gpt4 key购买 nike

假设我有一个包含一些值的数组:

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”获得过滤值。认为我需要使用委托(delegate)或协议(protocol),但不知道如何以及在哪里。谢谢!

最佳答案

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

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

关于ios - 从另一个 ViewController 访问数组并对其进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42139726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com