产生字典功能的问题

时间:2018-12-18 05:53:55

标签: ios swift dictionary

有一个像这样的功能……

func getCricketerList() {
    presenter?.cricketerListDidFetch(cricketerList: getAllCricketerDetail())
  }

在这里,getAllCricketerDetail()表示为……

func getAllCricketerDetail() -> [Cricketer] {
    var cricketerList = [Cricketer]()
    let allCricketerDetail = Common.generateCricketerList()
    for cricketer in allCricketerDetail {
      cricketerList.append(Cricketer(attributes: cricketer))
    }
    return cricketerList
  }

Common.generateCricketerList()的给出方式如下……

class Common: NSObject {

  class func generateCricketerList() -> [[String: String]] {
    return [["name": "Sachin Tendulkar","country":"India"],["name":"Brett Lee","country":"Australia"],["name":"Wasim Akram","country":"Pakistan"],["name":"Sourav Ganguly","country":"India"],["name":"Jonty Rhodes","country":"South Africa"]]
}
}

这很好。在其他地方,我正在尝试实现类似的功能。为此,我定义了一个名为Common2的类。现在,我要在此类中使用3个键/值对,即名称,描述和图像。我给的是这样的……

class Common2: NSObject {

  func generateCricketerDetailList() -> [[String:Any]] {
    return [["name": "Sachin Tendulkar","description":"add description here","image": UIImage(named: "Sachin.jpeg")!],["name":"Sourav Ganguly","description":"add description here","image":UIImage(named: "sourav.jpeg")!],["name":"Adam Gilchrist","description":"add description here","image":UIImage(named: "adam.jpeg")!],["name":"Jonty Rhodes","description":"add description here","image":UIImage(named: "adam.jpeg")!],["name":"Wasim Akram","description":"add description here","image":UIImage(named: "wasim.jpeg")!]]
  }
}

现在,当我尝试在函数中实现Common2时,会得到如下建议: enter image description here

现在,如果我单击突出显示的选项,则会得到类似这样的信息...

enter image description here

我该怎么办...?我在这里做错什么了...?

我在generateCricketerDetailList()中定义的函数Common2也是正确的吗?

2 个答案:

答案 0 :(得分:1)

您忘记使它像另一个函数一样成为类函数...

class func generateCricketerDetailList() -> [[String:Any]] {
    return [["name": "Sachin Tendulkar","description":"add description here","image": UIImage(named: "Sachin.jpeg")!],["name":"Sourav Ganguly","description":"add description here","image":UIImage(named: "sourav.jpeg")!],["name":"Adam Gilchrist","description":"add description here","image":UIImage(named: "adam.jpeg")!],["name":"Jonty Rhodes","description":"add description here","image":UIImage(named: "adam.jpeg")!],["name":"Wasim Akram","description":"add description here","image":UIImage(named: "wasim.jpeg")!]]
}

与问题无关,我建议您将信息存储在结构而不是字典中。除非您出于这个问题而试图模仿api响应。

答案 1 :(得分:1)

您了解类和实例的基本OOP概念吗? generateCricketerDetailList是一个 instance 方法,但是您试图像它是 class 方法一样调用它。