0

I'm migrating a project from Swift 2.2 to Swift 3 and ran into the following issue.

I have a function testing if a given input is of type AnyObject.
A simplified implementation could look like this:

func testIfIsObjectType(input: Any?) -> Bool {
    if input is AnyObject {
        return true
    }
    return false
}

In Swift 2.2, the following returns false.

let intValue = 3
let result = testIfIsObjectType(input: intValue)
print(result)

In Swift 3.3, it returns true.

The issue is caused by the fact, that all types (of type Any) can be converted to AnyObject now.

For example in Swift 3 you can now write:

let someType: Any = 1
let someObject = someType as AnyObject

Notice the as instead of as? or as!, which had to be used in Swift 2.

How do I check if the input is of type AnyObject, so the function will return false as in Swift 2.

Solution:

func testIfIsObjectType(input: Any?) -> Bool {
    if type(of: input) is AnyClass {
        return true
    }
    return false
}
florieger
  • 1,310
  • 12
  • 22
  • I searched for duplicates upfront, but was not able to find it, thanks for pointing me at this :) – florieger Mar 20 '17 at 10:34
  • @Hamish, the solution to the other question is no longer working. My question is about the Release Version of Swift 3, not beta builds. – florieger Mar 20 '17 at 10:42
  • Hmm, [the example in the answer](http://stackoverflow.com/questions/39184911/check-if-any-value-is-object) given is still working fine for me in both Swift 3.0.2 and Swift 3.1 in both -Onone and -O builds. I assume the problem you're having is due to the fact that `input` is typed as `Any?` aka `Optional`, which is certainly not an `AnyObject`. Given the other Q&A doesn't answer this exact question, I'll re-open. – Hamish Mar 20 '17 at 10:47
  • 2
    Really you just need to unwrap it, and the `type(of: input) is AnyClass` check should work again – `if let input = input, type(of: input) is AnyClass { return true }` should work. – Hamish Mar 20 '17 at 10:59
  • @Hamish, you're right, I incorrectly used `AnyObject` instead of `AnyClass`. Thanks for letting me know. I edit my question, to show the solution. – florieger Mar 21 '17 at 13:10

0 Answers0