0

I've been using CocoaLumberjack in Swift and Obj-C for years with pod 'CocoaLumberjack/Swift'.

I'm converting code from Obj-C to Swift and can't figure out how to translate this into Swift:

- (void)functionThatGetsCalledAlot {
  if (ddLogLevel & DDLogLevelVerbose) {
      DDLogVerbose(@"Log message");
      ...Many more log statements...
  }
}

I only use this in rare performance sensitive cases where I only want to execute some block of code based on the log level. The condition will be true if the dynamic log level, ddLogLevel, includes DDLogLevelVerbose which is true for DDLogLevelVerbose and DDLogLevelAll.

How do I write this in Swift?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jesse
  • 1,667
  • 12
  • 16
  • Possible duplicate: https://stackoverflow.com/questions/24112347/declaring-and-using-a-bit-field-enum-in-swift – Popmedic Jul 10 '18 at 20:40
  • 2
    Please use the native `os_log` instead of this horrible framework. –  Jul 11 '18 at 07:58

2 Answers2

3

I imported only little part of CocoaLumberjack, but this should work same as the Objective-C code above.

if (ddLogLevel.rawValue & DDLogLevel.verbose.rawValue) != 0 {
    ...    
}

(ADDITION)

But as far as I checked the original definition, this code (and your Objective-C code) returns true for all predefined log levels.

You may need to write something like this to hit only DDLogLevelVerbose and DDLogLevelAll.

(Objective-C)

if (ddLogLevel & DDLogFlagVerbose) {
    ...
}

(Swift)

if (ddLogLevel.rawValue & DDLogFlag.verbose.rawValue) != 0 {
    ...
}
OOPer
  • 47,149
  • 6
  • 107
  • 142
2

The swifty thing to use here would be an OptionSet type. Log levels are perfectly suited for this, but unfortunately in this case it is bridged from ObjC as an enum.

Since the underlying DDLogFlag conforms to OptionSet, we can build a workaround:

extension DDLogLevel {
    var flag: DDLogFlag {
        return DDLogFlag(rawValue: rawValue)
    }
}

which can then be used like this:

let logLevel = DDLogLevel.all

if logLevel.flag.contains(.verbose) {
    print("Verbose is on")
}
Xavier Lowmiller
  • 1,381
  • 1
  • 15
  • 24
  • 1
    (Corrected)I believe you can defined the extension as `var flag: DDLogFlag {return DDLogFlag(rawValue: self.rawValue)}`. The checking code is not equivalent to the OP's code, but it seems yours is the right answer. – OOPer Jul 10 '18 at 22:27
  • I knew there had to be an easier way to do this! I'm updating my answer, thank you! – Xavier Lowmiller Jul 11 '18 at 07:31
  • 1
    @XML and @OOPer Thanks for helping me understand the relationship between the flags and the log level. I went with `if DDLogFlag(ddLogLevel).contains(.verbose)` which is equivalent to the above. – Jesse Jul 12 '18 at 01:43