Using type(of:)
You can use type(of:)
to find out what type of variable is in a variable of type Any
.
let a: Any = "hello"
print(type(of: a)) // String
let b: Any = 3.14
print(type(of: b)) // Double
import Foundation
let c: Any = "hello" as NSString
print(type(of: c)) // __NSCFString
let d: Any = ["one": 1, "two": "two"]
print(type(of: d)) // Dictionary<String, Any>
struct Person { var name = "Bill" }
let e: Any = Person()
print(type(of: e)) // Person
Using classForCoder
classForCoder
is still there, and you can cast a value of type Any
to AnyObject
, but if the value is a Swift value type, you'll get a converted result and not the original type:
import Foundation // or import UIKit or import Cocoa
let f: Any = "bye"
print((f as AnyObject).classForCoder) // NSString
print(type(of: f)) // String
let g: Any = 2
print((g as AnyObject).classForCoder) // NSNumber
print(type(of: g)) // Int
let h: Any = [1: "one", 2: 2.0]
print((h as AnyObject).classForCoder) // NSDictionary
print(type(of: h)) // Dictionary<Int, Any>
struct Dog { var name = "Orion" }
let i: Any = Dog()
print((i as AnyObject).classForCoder) // _SwiftValue
print(type(of: i)) // Dog
// For an object, the result is the same
let j: Any = UIButton()
print((j as AnyObject).classForCoder) // UIButton
print(type(of: j)) // UIButton