Imagine a class Fruit:
class Fruit: NSObject {
override var description:String {
return super.description
}
}
var apple = Fruit()
var banana = Fruit()
print(apple) // Output: <MyProject.Fruit: 0x7fa719627e00>
print(banana) // Output: <MyProject.Fruit: 0x7fa71962dab0>
Question: How can you mimic this ouput?
I currently have the following:
class Fruit: NSObject {
override var description:String {
print(super.description)
return "<\(NSStringFromClass(self.dynamicType)): 0x\(String(self.hash, radix:16))>"
}
}
Which now outputs the following:
<MyProject.Fruit: 0x7fb958c289a0>
<MyProject.Fruit: 0x7fb958c289a0>
<MyProject.Fruit: 0x7fb958c22df0>
<MyProject.Fruit: 0x7fb958c22df0>
As you can see the output is the same which is what I wanted. Now I am wondering if this is the proper way to mimic it's output or that I am overlooking something as mentioned in the comments below.
Credits: Matt, Martin R and Vacawama
Use
String(self.hash, radix:16)
. You might need to prefix the0x
yourself.Any subclass of
NSObject
inherits thedescription
method ofNSObject
(which is defined in theNSObjectProtocol
):This "default implementation" prints the class name and the memory address of the object, see for example Friday Q&A 2013-01-25: Let's Build NSObject, where it is shown how the Objective-C implementation could look like:
The
%p
format prints the value of a pointer as a hexadecimal number, preceded by0x
.To mimic that in Swift, we can use
String(reflecting: self.dynamicType)
which returns the fully-qualified class name as a string, andunsafeAddressOf(self)
which returns a pointer to the storage of the object.Example (using square brackets
[]
to demonstrate that the overridden method is used):This works for "pure Swift classes" as well, because no Foundation methods are used:
Note that (as already mentioned in above comments), the hash value of an object is not necessarily identical to the memory address. A simple example is
NSArray()
whose hash value is just the number of elements:Update for Swift 3: