Printing a variable memory address in swift

前端 未结 15 1072
天涯浪人
天涯浪人 2020-11-28 01:16

Is there anyway to simulate the [NSString stringWithFormat:@\"%p\", myVar], from Objective-C, in the new Swift language?

For example:

le         


        
15条回答
  •  庸人自扰
    2020-11-28 01:34

    If you just want to see this in the debugger and not do anything else with it, there's no need to actually get the Int pointer. To get the string representation of an object's address in memory, just use something like this:

    public extension NSObject { // Extension syntax is cleaner for my use. If your needs stem outside NSObject, you may change the extension's target or place the logic in a global function
        public var pointerString: String {
            return String(format: "%p", self)
        }
    }
    

    Example usage:

    print(self.pointerString, "Doing something...")
    // Prints like: 0x7fd190d0f270 Doing something...
    

    Additionally, remember that you can simply print an object without overriding its description, and it will show its pointer address alongside more descriptive (if oft cryptic) text.

    print(self, "Doing something else...")
    // Prints like:  Doing something else...
    // Sometimes like: <_TtCC14__lldb_expr_668MyModule7MyClass: 0x7fd190d0f270> Doing something else...
    

提交回复
热议问题