In Swift (5), how to I pass an "Any..." parameter to a print() statement without it printing as an array?

259 views Asked by At

I have a global enum I use for global functions that I only want to run when the app is in debug. It looks something like this:

public enum Debug {
    static func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
        #if DEBUG
        Swift.print(items, separator: separator, terminator: terminator)
        #endif
    }
}

However, when I use

Debug.print(35)

the output is

["35"]

What I want is for the output to look just like a regular print statement:

35

Anyone know what I'm doing wrong or could do different?

It kind of looks like I have to "unpack" the items parameter and put each one in the print statement individually, but that seems like the wrong approach.

public enum Debug {
    static func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
        #if DEBUG
        for item in items {
            Swift.print(item, terminator: separator)
        }
        Swift.print("", terminator: terminator)
        #endif
    }
}

This works...but makes me cringe. There's got to be a better solution...

1

There are 1 answers

9
Leo Dabus On BEST ANSWER

You can simply map your items into strings, join them with the separator and print the resulting string:

public enum Debug {
    static func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
        #if DEBUG
        Swift.print(items.map({String(describing: $0)}).joined(separator: separator), terminator: terminator)
        #endif
    }
}

Or simply: