LoginSignup
5
4

More than 5 years have passed since last update.

[Swift] デバッグ時だけ出力

Last updated at Posted at 2017-02-12

おそらく、もう何度目だと言われそうなものですが、DEBUGマクロが有効な時のみコンソールに出力する関数群です。

Swift.print などをオーバーライドする方法があったりしますが、リリース時にも出力したい場合、Swift.printとしなければならないのが面倒臭いため、クラスにまとめました。(Swiftは任意のネームスペースが持てないので)

また、DebugクラスにまとめたことでDubegで検索するだけですぐ見つかります。

Debug.debugPrintの出力はSwift.debugPrintの出力とは完全には一致していません。

class Debug {
    private struct Args: CustomStringConvertible, CustomDebugStringConvertible {
        let args: [Any]
        let separator: String
        var description: String {
            return args.map { "\($0)" }.joined(separator: separator)
        }
        var debugDescription: String {
            return args
                .map { ($0 as? CustomDebugStringConvertible)?.debugDescription ?? "\($0)" }
                .joined(separator: separator)
        }
    }

    class func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
        #if DEBUG
            Swift.print(Args(args: items, separator: separator), separator: separator, terminator: terminator)
        #endif
    }

    class func debugPrint(_ items: Any..., separator: String = " ", terminator: String = "\n") {
        #if DEBUG
            Swift.debugPrint(Args(args: items, separator: separator), separator: separator, terminator: terminator)
        #endif
    }

    class func dump<T>(_ value: T, name: String? = nil, indent: Int = 0, maxDepth: Int = Int.max, maxItems: Int = Int.max) -> T {
        #if DEBUG
        return Swift.dump(value, name: name, indent: indent, maxDepth: maxDepth, maxItems: maxItems)
        #else
        return value
        #endif
    }
}

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4