【问题标题】:How to pass an NSDictionary to a function and return another NSDictionary in Swift 2如何将 NSDictionary 传递给函数并在 Swift 2 中返回另一个 NSDictionary
【发布时间】:2016-01-22 16:16:34
【问题描述】:

我正在尝试将 businesses(一个 NSDictionary)传递给一个函数,该函数遍历它并将选定的业务(也是一个 NSDictionary)返回给视图控制器。我无法在 Swift 中设置正确的调用和完成处理程序。我认为我没有在我的函数中正确处理业务字典的输入。

使用下面的代码,我收到一个错误,我在调用中有一个额外的参数。我是否需要将调用包装在 do/try/catch 中?我是 Swift 新手,对使用完成处理程序和将项目传递给函数的不同方法有点困惑。我发现的大多数关于堆栈溢出的问题都与如何使用 NSURLSession 相关,并且没有那么有帮助。如果这更容易,很高兴指出文档或相关博客文章的方向。谢谢。

ViewConteroller,我在这里调用函数并传递业务字典:

FindBar.searchForOpenBar(businesses) {(selectedBar) -> Void in     
    print(selectedBar)
}

从 FindBar 那里选择返回哪个栏以供视图控制器使用的逻辑(尚未实现)。

class FindBar {
    typealias Completion = (selectedBar:NSDictionary) -> Void
    func searchForOpenBar(businesses: NSDictionary, completion: Completion) {

        //iterate through the businesses and select the bar
        for business in businesses {

            //temp. hard-coded selection
            foundBar = ["name":"Dive Bar", "address":"123 Main St"]

        }

    //send selected bar back view controller.
    completion(selectedBar: foundBar)

}

【问题讨论】:

  • 看起来您正在调用类方法FindBar.searchForOpenBar(…,但该方法被声明为实例方法。 PS:如果字典真的只包含字符串,请使用 Swift 字典 [String:String]
  • @vadian,所以我可以使用类型方法并将func searchForOpenBar 更改为class func searchForOpenBar?关于 Swift 字典,我确实有一些 Int 和 Floats,所以我认为我需要保留它 NSDictionary。
  • 是的,就像 Breek 的回答中描述的那样。只有在别无选择的情况下,我才会使用NSDictionary。 Swift 集合类型更加通用。带有String 键和各种值类型的字典是[String:AnyObject] PS:自定义structclass 可能仍然比任何字典都好。
  • 感谢@vadian 的额外提示。使用 NSDictionary 一直很困难。我来看看 swift 版本。

标签: ios swift function nsdictionary


【解决方案1】:

在您的 FindBar 类中,将 func searchForOpenBar 更改为 class func searchForOpenBar

class FindBar {
    typealias Completion = (selectedBar:NSDictionary) -> Void
    class func searchForOpenBar(businesses: NSDictionary, completion: Completion) {

        //iterate through the businesses and select the bar
        for business in businesses {

            //temp. hard-coded selection
            foundBar = ["name":"Dive Bar", "address":"123 Main St"]

        }

    //send selected bar back view controller.
    completion(selectedBar: foundBar)

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2010-12-11
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多