Swift arrays and contains, how to determine if a collection contains an object or value?

后端 未结 3 1708
暖寄归人
暖寄归人 2020-12-09 15:25

I\'m at it again with swift arrays and containsObject provided by NSArray only!

I bridge the swift array to NSArray to do that contains:

extension Ar         


        
相关标签:
3条回答
  • 2020-12-09 15:37

    Generally, when you want to have an array that contains a custom object or struct, and you want to work with "contains" function, your class or struct should be conformed to "Equatable" protocol and you should implement the "==" function for later comparisons...

    struct booy: Equatable{
    static func == (lhs: booy, rhs: booy) -> Bool {
        return lhs.name == rhs.name
    }
    
    var name = "abud"
    }
    
    let booy1 = booy(name: "ali")
    let booy2 = booy(name: "ghasem")
    
    var array1 = [booy]()
    array1.append(booy1)
    array1.append(booy2)
    
    let booy3 = booy(name: "ali")
    
    if array1.contains(booy3){
        print("yes") }
    
    0 讨论(0)
  • 2020-12-09 15:38

    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")
    
    }
    
    0 讨论(0)
  • 2020-12-09 15:40

    Swift 1:

    let array = ["1", "2", "3"]
    let contained = contains(array, "2")
    println(contained ? "yes" : "no")
    

    Swift 2, 3, 4:

    let array = ["1", "2", "3"]
    let contained = array.contains("2")
    print(contained ? "yes" : "no")
    
    0 讨论(0)
提交回复
热议问题