通过 Segue 将数据传递给 new ViewController

Passing data to new ViewController through Segue

我正在尝试通过 segue 传递一串数据。 JSON 数据已使用 JSON 解码器解析并正确显示在控制台中。一切正常,除了当我尝试将数据传递给详细信息时 ViewController 我要么没有收到数据,要么收到错误。我正在使用 prepareForSegue 来传递数据。

这是 ViewController 的代码:

var nowPlaying = [Results]()
var searchTitle = [Results]()

struct NowPlaying: Codable {
    let results: [Results]
}

struct Results: Codable {
    let title: String
    let poster_path: String?
    let id: Int
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    var films: [Results]

    if searchBar.text == "" {
        films = [nowPlaying[indexPath.row]]
    }

    print("\(films)")

    performSegue(withIdentifier: "detailsSegue", sender: films)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "detailsSegue" {
        if let detailView = segue.destination as? DetailsView {
                let filmCell = sender as? Results
                detailView.filmId = filmCell!.id
                print("\(filmCell!.id)")
        }
    }
}

我在 detailView.filmId = filmCell.id

处遇到错误

Cannot assign value of type 'Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

这是为 print("\(films)") 打印到控制台的内容:

[Film_Bee.FilmsViewController.Results(title: "Venom", poster_path: 
Optional("/2uNW4WbgBXL25BAbXGLnLqX71Sw.jpg"), id: 335983)]

print("\(filmCell!.id)")

未打印任何内容

如果在解析和选择单元格时找到它,我不确定为什么它没有在结果中找到它。

这是我在 DetailsView 中的代码:

class DetailsView: UIViewController {

let homepage = FilmsViewController()

var filmId = 0

var filmDetails = [Details]()

struct Results: Codable {
    let title: String
    let poster_path: String?
    let id: Int
}

struct Details: Codable {
    let title: String
    let poster_path: String
}

override func viewDidLoad() {
    super.viewDidLoad()

    print(filmId)

}

你定义

var films: [Results]

然后调用

performSegue(withIdentifier: "detailsSegue", sender: films)

然后投

let filmCell = sender as? Results

这将不起作用,因为 Results 不是 [Results],决定你是想要一个 Result 的数组还是只需要一个。

重新考虑您的 singular/plural 命名。你要传一个片子,不是数组

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let film : Results // singular form `Result` is less confusing

    if searchBar.text.isEmpty {
        film = nowPlaying[indexPath.row]
    } else {
        film = searchTitle[indexPath.row]
    }

    print("\(film)")

    performSegue(withIdentifier: "detailsSegue", sender: film)

}