Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Array - use "Contains" of type AnyObject

Tags:

ios

swift

I want to use function contains on 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 the error:

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

enter image description here

like image 886
Khawar Avatar asked Dec 31 '14 12:12

Khawar


People also ask

How to check contains in array in Swift?

The contains() method returns: true - if the array contains the specified element. false - if the array doesn't contain the specified element.

Can array have different data types in Swift?

Here, [Int]() specifies that the empty array can only store integer data elements. Note: In Swift, we can create arrays of any data type like Int , String , etc.

What is AnyObject?

You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.


1 Answers

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

if (resultArray as NSArray).containsObject(AnyObjectOfAnyType) {
     // Do something
}
like image 95
trevorj Avatar answered Sep 22 '22 10:09

trevorj