问题
If you run the following in Playgroud
class Test {
var description:String {
return "This is Test"
}
}
class Test1:NSObject {
override var description:String {
return "This is Test"
}
}
let t = Test()
println(t)
let t1 = Test1()
println(t1)
you see that the first println will output some debugger blurb while the second echoes the contents of description.
So: is there a way that "normal" classes will be treated the same way as subclasses of NSObject so println will respect the contents of a description property?
回答1:
From the println() API documentation:
/// Writes the textual representation of `object` and a newline character into
/// the standard output.
///
/// The textual representation is obtained from the `object` using its protocol
/// conformances, in the following order of preference: `Streamable`,
/// `Printable`, `DebugPrintable`.
///
/// Do not overload this function for your type. Instead, adopt one of the
/// protocols mentioned above.
func println<T>(object: T)
So in order to get a custom println() representation, your class must (e.g.) adopt the Printable protocol explicitly:
class Test : Printable {
var description:String {
return "This is Test"
}
}
However, this does not work in a Playground of Xcode 6.1.1. It has been fixed in Xcode 6.3 beta. From the release notes:
• Adding conformances within a Playground now works as expected, ...
I could not find this in the API headers, but it seems that NSObject
(and its subclasses) are already known to conform to Printable.
Therefore the custom description works for your Test1 class.
In Swift 2 (Xcode 7), the Printable protocol has been renamed
to CustomStringConvertible:
class Test : CustomStringConvertible {
public var description:String {
return "This is Test"
}
}
let t = Test()
print(t)
// This is Test
回答2:
This is because you are printing out an instance of class. In swift, a class is not a default subclass of NSObject . To make a class a subClass of NSObject you have to specify it like you have done for the second class. Here's the modified code :
class Test {
var description:String {
return "This is Test"
}
}
class Test1:NSObject {
override var description:String {
return "This is Test"
}
}
let t = Test()
println(t.description)
let t1 = Test1()
println(t1)
Here's a quote from The Swift Programming Language,
Swift classes do not inherit from a universal base class. Classes you define without specifying a superclass automatically become base classes for you to build upon.
来源:https://stackoverflow.com/questions/28589785/getting-description-like-nsobject