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
}