【问题标题】:Type of expression is ambiguous without more context - .filter没有更多上下文,表达式的类型是模棱两可的 - .filter
【发布时间】:2017-04-16 10:28:21
【问题描述】:

我正在尝试过滤我的搜索栏,但我遇到了问题。我按照教程复制并粘贴了这段代码,但我从行中收到错误“表达式类型不明确,没有更多上下文”

return mod.profileNameLabel.lowercased().contains(text.lowercased())

我正在使用 swift 3 和 Xcode 8。我已将代码粘贴在下面:

var intialProfiles = NSMutablearray()

var profiles = NSMutablearray()

func filterTableView(ind:Int,text:String) {
        switch ind {

        case selectedScope.Name.rawValue:

            //fix of not searching when backspacing
            profiles = intialProfiles.filter(using: { (mod) -> Bool in
            return mod.profileNameLabel.lowered().contains(text.lowercased())
            })
            self.searchTableView.reloadData()

【问题讨论】:

  • NSMutableArray 在 Swift 中是可怕的。使用原生 Swift Array.

标签: ios swift3 xcode8


【解决方案1】:

NSMutableArray.filter 接受 NSPredicate 作为参数,而不是您传入的 (Profile) -> Bool 闭包类型。

我建议您使用 swift 数组而不是 NSMutableArray

我假设数组包含Profile 对象。如果没有,只需将下面代码中的单词 Profile 替换为它所拥有的任何类型。

var intialProfiles = [Profile]()

var profiles = [Profile]()

func filterTableView(ind:Int,text:String) {
        switch ind {

        case selectedScope.Name.rawValue:

            //fix of not searching when backspacing
            profiles = intialProfiles.filter { $0.profileNameLabel.lowered().contains(text.lowercased()) }
            self.searchTableView.reloadData()

如果你坚持使用NSMutableArray,这里是你需要使用的谓词:

initialProfiles.filter(using: NSPredicate(format: 
    "profileNameLabel contains[c] %@", "Hello"))

【讨论】:

  • 感谢您的回复。我尝试了您推荐的谓词代码,它删除了错误,但是当我运行它时,代码没有按照它假设的方式运行,即 searchBar 没有过滤数组。您知道为什么它没有按应有的方式运行可能是什么问题吗?另外我忘了提到我的数组是由从 firebase 检索到的数据组成的,这就是我使用 NSMutableArray 的原因。
  • 您可以轻松地将 NSMutableArray 转换为 swift 数组。仅通过查看您提供的代码,我无法找到它不起作用的原因。我需要更多你的代码来解决这个问题。也许你应该检查调用filterTableView 的方法。表视图数据源方法也可能是错误所在。还要检查filter 位是否被执行。 @j.iese
  • 好的,所以我仔细检查了过滤器位,它实际上根本没有执行。我放了一个打印语句,只有那个打印正在执行。代码如下 func filterTableView(ind:Int,text:String) { switch ind { case selectedScope.Name.rawValue:profiles.filter(using: NSPredicate(format: "profileNameLabel contains[c] %@", "Hello" )) self.searchTableView.reloadData() 打印(“搜索”)
  • 我也从 func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { profiles = NSMutableArray() self.searchTableView.reloadData() }else { filterTableView( ind: searchBar.selectedScopeButtonIndex, text: searchText) } }
  • @j.iese 然后检查是否调用了搜索栏委托方法。如果没有调用,请检查您是否将搜索栏的代理设置为self。只需单步执行代码,您应该能够找到错误所在。这是基本调试,超出了此问题的范围。如果您认为我的回答可以回答您的问题,请考虑通过单击该复选标记来接受它!
猜你喜欢
  • 1970-01-01
  • 2017-04-15
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
相关资源
最近更新 更多