Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a variable memory address in swift

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

For example:

let str = "A String" println(" str value \(str) has address: ?") 
like image 931
apouche Avatar asked Jun 05 '14 11:06

apouche


People also ask

How do I print a variable address in Swift?

To get the (stack) address of a struct, build-in type or object reference. In Objective-C this would be [NSString stringWithFormat:@"%p", &o] or [NSString stringWithFormat:@"%p", &i] . s is struct. So if s is assigned to another variable s2 , the value will be copied and the returned address for s2 will be different.

How do you print a memory address of a variable?

To print the memory address, we use '%p' format specifier in C. To print the address of a variable, we use "%p" specifier in C programming language.


1 Answers

Note: This is for reference types.

Swift 4/5:

print(Unmanaged.passUnretained(someVar).toOpaque()) 

Prints the memory address of someVar. (thanks to @Ying)


Swift 3.1:

print(Unmanaged<AnyObject>.passUnretained(someVar as AnyObject).toOpaque()) 

Prints the memory address of someVar.


like image 83
Woodstock Avatar answered Sep 19 '22 14:09

Woodstock