实例成员不能用于类型 - Swift 错误

Instance member cannot be used on type - Swift error

让我解释一下到目前为止我的应用程序...

我将 Pokemon 数据存储在字典数组 objects 中。

1st VC -> 用户选择一个 Pokemon 角色,所选 Pokemon 的详细信息将添加到另一个词典中。

然后用户按下一个按钮,将他们带到第二个 VC (collectionViewController) -> 他们选择的口袋妖怪数据也被传递并存储到一个名为 selectedPokemonObject 的变量中

如果我 print(selectedPokemonObject) 我可以看到用户选择的预期数据,所以我知道数据正在传递到第二个 VC。

collectionViewController 中,我想显示与用户选择的 "type" 相同的口袋妖怪。

我创建了一个过滤这个的变量:

var filteredObjects = objects.filter{ ([=18=]["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{ ([=11=]["type"] == selectedPokemonObject["type"])}.filter{ ([=11=]["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

}
}

更新

objects 数据作为全局变量存储在名为 Data.swift 的文件中,因此我可以在任何地方访问它。

有些地方我不同意您的代码,但我会首先帮助您修复错误。 Swift 不喜欢你使用实例化变量来帮助你实例化另一个变量。 Swift 无法知道先初始化哪个。而是将两者都初始化为空,并在 viewDidLoad() 中设置它们的值,这将在 UITableViewDataSource/Delegate 方法之前 运行 。确保 filteredObjectsobjects 是相同的结构。即 [[String : String]]

var selectedPokemonObject = [String:String]()
var filteredObjects = [[ String:String ]]()

所以你过滤的方式是错误的。你基本上是在说 "I filter out all pokemon except those that have the same first type as my pokemon. Then I filter them out again until I get ONLY the pokemon out of that small that have the same second type." 看到我对口袋妖怪了解一点,很少有相同类型的。这会给你一个有限的 Poke 领域。而是尝试这样的事情。

override func viewDidLoad() {
   super.viewDidLoad()

   filteredObjects = objects.filter { [=11=]["type"] == selectedPokemon["type"] || [=11=]["typeTwo"] == selectedPokemon["typeTwo] }
}

这个过滤是说如果类型一或类型二匹配,它们将出现在我们的过滤器列表中。或者,您可以尝试添加语句,如果所选口袋妖怪的类型 1 与口袋妖怪的类型 2 匹配,它将进入过滤等