Swift Array - Use Contains of AnyObject Type

I want to use the contains function for an array of type AnyObject

 import UIKit var resultArray: Array<AnyObject> = Array() resultArray.append(50) resultArray.append(false) resultArray.append("Test string") let found = contains(resultArray, 50) 

I get an error message:

 Type 'AnyObject -> L' does not conform to protocol 'IntegerLiteralConvertible' 

enter image description here

+6
source share
3 answers

I agree with the comments and other answer; AnyObject not good practice, but if you really want to use AnyObject , you can treat your AnyObjects array as an NSArray , and then use the containsObject() function:

 if (resultArray as NSArray).containsObject(AnyObjectOfAnyType) { // Do something } 
+9
source

You should probably use Any in this example, since you are holding non-classical types - otherwise you will do an implicit conversion to NSThing s.

But this is a non-ObjC-interop way to do this:

 let found = contains(resultArray) { ($0 as? Int) == 50 } 
+4
source

You can use the is keyword to distinguish between types, and then use the code snippet using the Airspeed Velocity speed above to search ... Here is an example that you can modify and add additional types if necessary:

 if resultArray[0] is String { found = contains(resultArray) { ($0 as? String) == "hello" } } else if resultArray[0] is Int { found = contains(resultArray) { ($0 as? Int) == 50 } } 

NOTE. You said that your array will only contain 1 type at a time - this is important.

0
source

Source: https://habr.com/ru/post/980367/


All Articles