创建搜索栏时出错:条件绑定的初始化程序必须具有选项类型,而不是'字符串'
问题描述:
我试图在TableView中创建搜索栏。我能够让搜索栏进入用户界面,但我正在努力寻找功能逻辑。我一直在关注教程,但仍然在代码中出现错误。创建搜索栏时出错:条件绑定的初始化程序必须具有选项类型,而不是'字符串'
所有数据都通过json文件正确读取。'
我在'filterContent(for:)'函数中收到错误。该错误读取“条件绑定的初始化程序必须具有可选类型,而不是'字符串'”
以下是我的TableView类中的相关代码。 (请注意标有注释的错误行)。
import UIKit
class LocationTableViewController: UITableViewController, UISearchResultsUpdating {
var locations = [Location]()
var searchController:UISearchController!
var searchResults = [Location]()
override func viewDidLoad() {
super.viewDidLoad()
searchController = UISearchController(searchResultsController: nil)
tableView.tableHeaderView = searchController.searchBar
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
}
func filterContent(for searchText: String) {
searchResults = locations.filter({ (location) -> Bool in
// The following line receives the error
if let name = location.name {
let isMatch = name.localizedCaseInsensitiveContains(searchText)
return isMatch
}
return false
})
}
func updateSearchResults(for searchController: UISearchController) {
if let searchText = searchController.searchBar.text {
filterContent(for: searchText)
tableView.reloadData()
}
}
答
这意味着:
location.name
是不可选的,但使用的是有条件的(让)语法。 这只适用于可选项,并且location.name不是可选项。
如果更改此:
if let name = location.name {
let isMatch = name.localizedCaseInsensitiveContains(searchText)
return isMatch
}
return false
这样:
let name = location.name
let isMatch = name.localizedCaseInsensitiveContains(searchText)
return isMatch
它会正确编译。无需“返回false”
感谢您的回答。我应该提到我已经尝试过这一点。应用程序构建,但是,它打开应用程序时崩溃。该日志读取'致命错误:意外地发现零,同时解开可选值。' – joshlorschy