我正在尝试通过segue传递一串数据。 JSON数据已使用JSONDecoder解析,并正确显示在控制台中。除了当我尝试将数据传递到详细信息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
无法分配类型为'Thread 1'的值:致命错误:展开一个可选值时意外发现nil
这是print("\(films)")
打印到控制台的内容:
[Film_Bee.FilmsViewController.Results(title: "Venom", poster_path:
Optional("/2uNW4WbgBXL25BAbXGLnLqX71Sw.jpg"), id: 335983)]
print("\(filmCell!.id)")
上没有任何内容
我不确定如果在解析和选择单元格时找到ID,为什么在结果中找不到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)
}
答案 0 :(得分:3)
您定义
var films: [Results]
然后致电
performSegue(withIdentifier: "detailsSegue", sender: films)
然后投射
let filmCell = sender as? Results
由于Results
不是[Results]
而不能正常工作,请确定是要使用Result
数组还是只需要一个数组。
答案 1 :(得分:1)
重新考虑您的单/复数命名。您想通过一部电影而不是一部电影
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)
}