Swift: Object Instance by Name

How to find a class instance name in other class in swift?

You can get variable name only in this way

class MyClass {
func printInstanceNameIn(user: User) {
let mirror = Mirror(reflecting: user)
for (label, value) in mirror.children {
if let value = value as? MyClass, value === self {
print(label!)
}
}
}
}

class User {
var firstObject: MyClass!
var secondObject: MyClass!
}

let u = User()
u.firstObject = MyClass()
u.secondObject = MyClass()
u.firstObject.printInstanceNameIn(user: u)

How to create an instance of a class from a String in Swift

You can try this:

func classFromString(_ className: String) -> AnyClass! {

/// get namespace
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String

/// get 'anyClass' with classname and namespace
let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!

// return AnyClass!
return cls
}

use the func like this:

class customClass: UITableView {}   

let myclass = classFromString("customClass") as! UITableView.Type
let instance = myclass.init()

Swift - how do I pass a type/object (name or instance) into a method and then (a) get the type (b) instantiate it?

You can use the .dynamicType property of an instance to get its type. Then you can call a required init method on it (or any other class/static method).

let theType = object.dynamicType
let newInstance = theType.init()

Note: This code compiles, depending on the type of object. If the type has a required init() method, it is safe to call on the dynamicType. However, it also appears that if the type is NSObject the compiler will let you call init() on the dynamicType even though a subclass may or may not have an init() method given how Swift initializer inheritance works. Arguably this is a bug in the compiler, so use this code with caution if you choose to do so. Thanks to @nhgrif for the discussion on the topic.

Swift. Refer to instance variables by string name

Not Swift-ish, as it's bypassing compile time type checking. Best option is to keep them all in a dictionary, and use a protocol to define allowed data types in the dictionary, but even that is rather poor

How do I get the class instance ID in Swift?

To get current function name use #function literal.

As for instance ID, looks like you have two options:

  1. Inherit from NSObject (UIKit classes inherit it anyways) so that class instances would have instance IDs:

    class MyClass: NSObject {
    override init() {
    super.init()
    print("[DBG: \(#function)]: \(self)")
    }
    }
  2. If your class does not inherit from NSObject you can still identify your instances by memory address:

    class Jumbo {
    init() {
    print("[DBG: \(#function)]: \(Unmanaged.passUnretained(self).toOpaque())")
    }
    }


Related Topics



Leave a reply



Submit