Reputation: 408
I'm trying to do some things in Swift involving run-time checking of types that get erased due to storing as Any (which I know sounds ugly but it's a narrow use-case and I have good-ish reasons). I ran into a weird problem that can be summed up with these examples:
This works under cli/REPL:
let pType: Any.Type = Int.self
if let x = 3 as? pType { print("found an int") }
However this does not work:
let pType: Any.Type = Int.self; if let x = 3 as? pType { print("found an int") }
And results in error: cannot find type 'pType' in scope
When building as a program, I get the same error in either form.
Can anyone explain why this does not work? And if there is any way around this? And if what I'm doing is just plain wrong, why does it work in REPL?
Upvotes: 1
Views: 297
Reputation: 534950
I think what you're looking for is some kind of generic. Perhaps like this:
func isThisObject<T>(_ object:Any, ofThisType type: T.Type) -> Bool {
return object is T
}
Examples:
let i : Any = 1
isThisObject(i, ofThisType:Int.self) // true
Or:
let s : Any = "Howdy"
isThisObject(s, ofThisType:Int.self) // false
Or you can omit the Any, it makes no difference.
Or, if actually doing the cast right there is important to you:
func tryToCast<T>(_ object:Any, toThisType type: T.Type) -> T? {
return object as? T
}
tryToCast(1, toThisType: Int.self) // 1
tryToCast("howdy", toThisType: Int.self) // nil
Upvotes: 1