type(of:) の使用
type(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
classForCoder の使用
classForCoder
はまだ存在し、型の値を にキャストできますがAny
、AnyObject
値が Swift 値型の場合、元の型ではなく変換された結果が得られます。
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