二元运算符'=='不能应用于'String?'类型的操作数和 '布尔' 的斯威夫特3

问题描述:

var is_searching: String? = nil 

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell   
{ 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) as! ProductCell 

    if is_searching == true 
    { 
     cell.lblBrndname?.text=(searched_array[(indexPath as NSIndexPath).row] as AnyObject).value(forKey: "brand_name") as? String 
     cell.Pdtimg?.image = UIImage(named: icon_Array[indexPath.row]) 

    } 
    else 
    { 
     cell.lblBrndname?.text=(Specarray[(indexPath as NSIndexPath).row] as AnyObject).value(forKey: "brand_name") as? String 
     cell.Pdtimg?.image = UIImage(named: self.icon_Array[indexPath.row]) 

    } 
    return cell 

} 
+0

问题是什么? – JeremyP

+1

你应该如何比较'String'是否为'true'?你只能比较一个String和另外一个String。 – nayem

+0

如何将字符串与布尔进行比较? –

变型isSearching

var is_searching: Bool = false 

的NSString有,你可以用一个boolValue属性:

if let is_searching = is_searching as? NSString, 
    is_searching.boolValue == true { 
    print("String is true") 
} else { 
    print("String is not true") 

但其他海报的想法是更好的。如果你可以重写你的代码,那么is_searching首先是一个更好的方法。