【问题标题】:SWIFT work with arrays and dictionariesSWIFT 使用数组和字典
【发布时间】:2018-06-30 12:42:38
【问题描述】:

我正在尝试通过数组中的 segue 将信息传递给第二个控制器:

var gists = [Gists]()

这就是我实现方法 prepare(for segue: 的样子

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "detailSegue" {
            if let indexPath = tableView.indexPathForSelectedRow {
                 guard let dvc = segue.destination as? DetailViewController else { return }
                dvc.filename = gists[indexPath.row].files.key // type String
                dvc.rawUrl = gists[indexPath.row].files.value // type String
            }
        }
    }

这是我的数组 gists 的转储:

▿ 2 elements
  ▿ GistShowApp.Gists
    ▿ description: Optional("mySecondGist")
      - some: "mySecondGist"
    ▿ files: 1 key/value pair
      ▿ (2 elements)
        - key: "gistfile1.txt"
        ▿ value: GistShowApp.DetailGist
          ▿ filename: Optional("gistfile1.txt")
            - some: "gistfile1.txt"
          ▿ rawUrl: Optional("https://gist.githubusercontent.com/VladimirKhuraskin/9ca2362c09cebcc16bd74f51f267231a/raw/74caacd3ad3eedb369a07b926327d2ef37e3eefc/gistfile1.txt")
            - some: "https://gist.githubusercontent.com/VladimirKhuraskin/9ca2362c09cebcc16bd74f51f267231a/raw/74caacd3ad3eedb369a07b926327d2ef37e3eefc/gistfile1.txt"
  ▿ GistShowApp.Gists
    ▿ description: Optional("helloWorldDemo")
      - some: "helloWorldDemo"
    ▿ files: 1 key/value pair
      ▿ (2 elements)
        - key: "gistfile1.txt"
        ▿ value: GistShowApp.DetailGist
          ▿ filename: Optional("gistfile1.txt")
            - some: "gistfile1.txt"
          ▿ rawUrl: Optional("https://gist.githubusercontent.com/VladimirKhuraskin/c510014b85a6bdfa302f1f3837893a7c/raw/4648e701849ee7d52fb685111a7f0e4323505a35/gistfile1.txt")
            - some: "https://gist.githubusercontent.com/VladimirKhuraskin/c510014b85a6bdfa302f1f3837893a7c/raw/4648e701849ee7d52fb685111a7f0e4323505a35/gistfile1.txt"
2018-06-30 15:30:26.336720+0400 GistShowApp[1889:720551] [Snapshotting] Snapshotting a view (0x134032c00, UIKeyboardImpl) that is not in a visible window requires afterScreenUpdates:YES.

也就是说,我有一个元素数组gists,每个元素都由一个字符串和一个字典组成。反过来,这个字典的类型是 [String: String]。而且我需要传递key和对应的value。

Xcode 在这些行上产生错误。如何正确书写?

dvc.filename = gists[indexPath.row].files.key
dvc.rawUrl = gists[indexPath.row].files.value

【问题讨论】:

    标签: arrays json swift dictionary


    【解决方案1】:

    gists[indexPath.row].files 是一本字典,因此您需要将 dvc.filenamedvc.rawUrl 设置为该字典中的一个条目,或者将整个字典传递给详细视图控制器。

    对于第一个选项:

    dvc.filename = gists[indexPath.row].files["gistfile1.txt"].filename
    dvc.rawUrl = gists[indexPath.row].files["gistfile1.txt"].rawURL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 2018-10-25
      相关资源
      最近更新 更多