Swift 2 Array Contains object?

后端 未结 4 1894
隐瞒了意图╮
隐瞒了意图╮ 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:41

    This answer isn't relevant for the OP's question, but might be helpful to others who are confronted with the Swift error message

    Cannot invoke 'contains' with an argument list of type '(whatever)'

    But first a quick quiz: Can you spot the problem here?

    internal class FrameworkAdminConnections {
    
       private var _localConnectionKeys = [Int]()
    
       ... other code omitted
    
       public func isLocalConnection(_ connectionKey : Int) {
          return _localConnectionKeys.contains(connectionKey)
       }
    }   
    

    Swift kept telling me I couldn't invoke contains() with an argument list of type (Int), which was a very unhelpful error message, and I don't dare admit how long it took me to finally figure it out.

    The real problem was that Swift's inference engine couldn't figure out what the result of the contains() method should be - because I'd stupidly not specified "-> Bool" on the isLocalConnection() method signature!

提交回复
热议问题