Xcode 8 beta 6: AnyObject replaced by Any: where is classForCoder?
Asked Answered
S

1

5

Xcode 8 beta 6 has replaced AnyObject by Any.

In some cases I used a.classForCoder for debugging reasons to see what's in it. With AnyObject this worked. With Any this doesn't work any more.

Now that I have to use Any: what is the preferred way to see what type is in a variable of type Any?

Casting to AnyObject appears not to be very useful since in many cases this is a String and String doesn't confirm to AnyObject any more since Xcode 8 beta 6.

Sarmentum answered 15/8, 2016 at 21:30 Comment(0)
A
9

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
Armington answered 15/8, 2016 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.