1

I'm trying to override the debugDescription property when displaying the value of NSDate objects in the Xcode debugger.

My extension code:

import Foundation

extension NSDate {
   public override var debugDescription: String {
      return "FOOFOOFOO" 
   }

   public func yeah() -> String {
      return "yeah!"
   }
}

I've confirmed that the file with my extension code is included in the test project targets as I'm able to call the yeah function and print it successfully in the debugger's output. However, I can't seem to get the debugDescription property to get used.

Note my actual goal is to do what I did in Objective-C previously (see this question for details), but struggling so far with how to do it in Swift.

Community
  • 1
  • 1
GusP
  • 2,454
  • 2
  • 23
  • 32

1 Answers1

4

the are two separate protocols in Swift

struct S : CustomStringConvertible, CustomDebugStringConvertible {
    var description: String {
        return "description"
    }
    var debugDescription : String {
        return "debug description"
    }
}

let s = S()
print(s)        // description
debugPrint(s)   // debug description

... thanks have to go to Leo !!!

import Foundation
extension NSDate: CustomDebugStringConvertible {
    public override var debugDescription: String {
            return "FOO"
    }
}

debugPrint(NSDate()) // FOO
user3441734
  • 16,722
  • 2
  • 40
  • 59
  • 1
    That works fine for me. I think my problem is more around specifically how to override `debugDescription` (or `description`) on `NSDate` objects via an `extension` method. – GusP Dec 15 '15 at 19:27
  • 1
    @GusP extensions may not contains stored properties, you may not redeclare any property in an extension. you can override the property of super class ... so, what you are trying to do is not possible. If you need some special behavior, you can still subclass NSDate and override debugDescription there. – user3441734 Dec 15 '15 at 19:36
  • 1
    @LeoDabus: That results in an error: "Redundant conformance of 'NSDate' to protocol 'CustomDebugStringConvertible'". – GusP Dec 15 '15 at 19:44
  • Pretty unfortunate if it's not possible. Doing the same thing in Objective-C was infinitely better than having to subclass NSDate throughout my code. I think I'd actually prefer just doing the conversions in my head than subclassing. Also, were you actually able to get Leo's code to compile successfully? – GusP Dec 15 '15 at 21:53
  • @GusP of course, what you can see in my example works for me as expected – user3441734 Dec 16 '15 at 03:48
  • Hmm, okay. Thanks for confirming. I get the error I mentioned above when trying that code. Will see if I can figure out why it doesn't work for me. – GusP Dec 16 '15 at 03:50