让我解释一下我的应用程序,到目前为止...实例成员不能在类型一起使用 - 斯威夫特错误
我存储在口袋妖怪数据和字典称为objects
的阵列。
1st VC - >用户选择一个宠物小精灵字符,并且所选口袋妖怪的细节被添加到另一个字典。
然后用户按下一个按钮,他们带到第二VC(collectionViewController
) - >他们选择的经过以及和存储到一个称为selectedPokemonObject
变量如果我print(selectedPokemonObject)
我可以看到数据作为小宠物数据预计用户选择,所以我知道数据传递给第二VC。
在collectionViewController
中,我想显示与用户选择的口袋妖怪相同的"type"
的口袋妖怪。
我创建了这个过滤的变量:
var filteredObjects = objects.filter{ ($0["type"] == selectedPokemonObject["type"])}
此代码不能正常工作 - 它给我的错误:
Instance member 'selectedPokemonObject' cannot be used on type 'CollectionViewController'
我不明白为什么这是。
我已经在这个问题上发布了一些问题,但无法理解他们中的任何一个 - 他们的回答对我的问题并没有真正的帮助,所以我希望对此有任何帮助。我如何在我的代码中使用它?
我完整的代码下面的CollectionViewController
:
class CollectionViewController: UICollectionViewController {
var selectedPokemonObject = [String:String]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Pokémon"
print(selectedPokemonObject)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
// MARK: UICollectionViewDataSource
var filteredObjects = objects.filter{ ($0["type"] == selectedPokemonObject["type"])}.filter{ ($0["typeTwo"] == selectedPokemonObject["typeTwo"])}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filteredObjects.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell
let object = filteredObjects[indexPath.row]
cell.pokemonName.text = object["name"]!
cell.pokemonImage.image = UIImage(named: "\(object["id"]!)"+"\(object["name"]!)")
return cell
}
}
UPDATE
objects
数据被存储在一个名为Data.swift
,所以我可以在任何地方访问它文件的全局变量。
几个问题。 “对象”在哪里申报?它是一个全局变量吗?另外,他们设置你的过滤器语句的方式是使得它只有pokemon和''typeTwo''字段的EMPTY字符串,但是如果它们有一个零或任何其他字符串,它将被过滤掉。 – NSGangster
@NSGangster我将更新添加到我的问题中,并修改了'typeTwo'错误(我之前正在玩弄它) - 谢谢 – Nick89
您是否尝试在过滤之前保存electionPokemonObject [“type”]以检查是否会工作?并分开这两个过滤器一步一步走? –