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:
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)")
}
}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
How to Fill Triangle in Swift Using Core Graphics
Need Clarification on Typealias Syntax in Swift
Swift: Switch Statement Fallthrough Behavior
How to Find Multiple Nsrange for a String from Full String iOS Swift
Cannot Convert Value of Type 'Nsmutablearray' to Expected Argument Type '[Skaction]'
Swift Unsafemutablepointer & Unsafemutablepointer<Unsafepointer<Sometype>>
Automatically Reload Tableviewcontroller on Rewind
Custom Markers Disappear on Zoomin The Map and Appear on Zoomout The Map with Clustering
How to Set a Known Position and Orientation as a Starting Point of Arkit
Closure Identity in Swift: Unregister Observing Closure
Actions Assigned to Nsmenuitem Dont Seem to Work
List Is Not Conforming to Encodable
Urlcomponents Queryitems Losing Percent Encoding When Mutated
Update UIapplicationshortcutitem from Extension
The "Funk" Sound When Hitting Escape Key in App
Understanding Optional Global Variables in Swift
How to Cache Cells and Also Reuse Cells in a Collectionview That Has Avplayers Embedded in Each Cell