Swift:无法将'[Any]'类型的值转换为指定类型'NSString'

时间:2017-11-15 23:06:45

标签: ios swift uicollectionview uisearchbar

概述:我有一个集合视图应用程序,其中包含多个plist中的几个项目,具体取决于用户选择的项目。 plist是一个包含多个数组的数组,每个数组中都有多个字符串。

问题:在使用搜索栏搜索我的馆藏(或plist)时,我在阅读教程时会收到此错误。

我知道这个搜索条形码用于查找字符串,而不是plist中另一个数组内的数组内的字符串。所以我正在寻找帮助来修复我的错误和代码。

错误:

  

无法将'[Any]'类型的值转换为指定类型'NSString'

这是造成错误的代码。

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = car.filter({ (text) -> Bool in
        let tmp: NSString = text // <-- ** Error is here **
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })

    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }

    self.finalCollectView.reloadData()
}

我的其余SearchBar代码

func createSearchBar() {

    let mySearchBar = UISearchBar()
    mySearchBar.showsCancelButton = false
    mySearchBar.placeholder = "Search"
    mySearchBar.delegate = self
    mySearchBar.alpha = 1
    mySearchBar.tintColor = UIColor.black
    mySearchBar.searchFieldBackgroundPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)

    self.navigationItem.titleView = mySearchBar
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

plist的代码

var filtered = [[Any]]()
var searchActive: Bool = false
var car = [[Any]]()
@IBOutlet weak var finalCollectView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.finalCollectView.delegate = self
    self.finalCollectView.dataSource = self

    readList(titlePlist: "car")
}

func readList(titlePlist: String) {

    let url = Bundle.main.url(forResource: titlePlist, withExtension: "plist")!
    do {
        let data = try Data(contentsOf:url)
        let sections = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[Any]]

        car = sections

    } catch {
        print("This error must never occur: Reading plist", error)
    }

plist如何看起来像

<plist> 
    <array>
        <array>
            <string>Name1</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name2</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name3</string>
            <string>Description</string>
        </array>
    </array>
</plist>

搜索栏需要搜索每个数组中的第一个字符串。谢谢!

2 个答案:

答案 0 :(得分:2)

如果您只想搜索car内部数组的第一个元素,则应使用flatMap来获取第一个元素。您还应该立即将元素强制转换为NSString,以避免必须在filter内投射。

filtered = car.flatMap({$0.first as? NSString})filter({ (text) -> Bool in...

但是,您对数据结构的选择相当奇怪。为什么你将car声明为[[Any]],当它只包含String时,内部数组看起来应该是字典而不是数组?我建议您将car声明为[[String:String]]并相应修改您的.plist文件。

答案 1 :(得分:1)

app.post("/api/events", function (req, res) { Helpers.geoLocate(req.body.location) .then(function (results) { Sport.create({ title: req.body.title, sport: req.body.sport, location: req.body.location, time: req.body.time, lat: results.lat, lng: results.lng, expireAt: req.body.time }).then(obj=>res.json(obj)); }); }); 中,将过滤修改为:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)