0

In my app, i'm declaring an array stored property as a variable. when i want to check if it contains and object, Xcode doesn't autocomplete. If i complete it manually it shows an error saying that it doesn't contain this method. I think it the array is not being mutable although it's declared as a var. Here is my code:

class someClass{
   var someArray = AnyObject[]()

   func someFunction{
     if someArray.containsObject("object") <--- error here
   }
}
1
  • containsObject is not a method on Array, its a method on NSArray. There should be a Swift equivalent method to do that Commented Jun 11, 2014 at 18:04

2 Answers 2

2

Your code contains a bunch of syntax errors:

  • There shouldn't be parentheses after class someClass
  • There should be parentheses after func someFunction

But the error you noticed is that there is no method containsObject on Array. You can do:

contains(someArray, "object")

or you can cast it to an NSArray:

(someArray as NSArray).containsObject("object")

Edit

As Rob Napier correctly points out, the first option will (of course) only work on String[], not on AnyObject[]. Swift really discourages mixed arrays.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this won't quite work as written. The array needs to be of type String, not AnyObject for the generic to figure it out (you can't construct an AnyObject). But this is still the right approach.
thanks all working well, but with this i don't know why Apple is advertising the language as being easier to learn than Objective-C. Personally, I still find OC having some advantages over Swift. i Found it more readable though. I don't know if any one agrees too.
1

Array doesn't have a method containsObject. That's a method of NSArray.

You can use the filter method for the find() function.

You could also cast the Array to NSArray then call the containsObject.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.