Search code examples
swiftdebug-symbolsprintln

Getting description like NSObject


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?


Solution

  • 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