Swift 2 Array Contains object?

后端 未结 4 2046
隐瞒了意图╮
隐瞒了意图╮ 2021-02-20 18:44

Why isn\'t this working? I can use array.contains() on a String but it doesn\'t work for an Object.

var array = [\"A\", \"B\", \"C\"]

array.contains(\"A\") //          


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 19:49

    Swift

    If you are not using object then you can user this code for contains.

    let elements = [ 10, 20, 30, 40, 50]
    
    if elements.contains(50) {
    
        print("true")
    
    }
    

    If you are using NSObject Class in swift. This variables is according to my requirement. you can modify for your requirement.

    var cliectScreenList = [ATModelLeadInfo]()
    var cliectScreenSelectedObject: ATModelLeadInfo!
    

    This is for a same data type.

    { $0.user_id == cliectScreenSelectedObject.user_id }
    

    If you want to AnyObject type.

    { "\($0.user_id)" == "\(cliectScreenSelectedObject.user_id)" }
    

    Full condition

    if cliectScreenSelected.contains( { $0.user_id == cliectScreenSelectedObject.user_id } ) == false {
    
    cliectScreenSelected.append(cliectScreenSelectedObject)
    
    print("Object Added")
    
    } else {
    
    print("Object already exists")
    
    }
    

提交回复
热议问题