Alec O
Alec O

Reputation: 1707

Swift: Extending functionality of print() function

Is it possible to extend the functionality of a Swift function? I would like appnd a single character onto every print() function in my program without having to create a brand new function and renaming every instance of print(). Is it possible to create an extension that will append an '*' onto every print instance?

The purpose of this is to create a way of flushing out all of the extra information that XCODE adds into the debugger. I am using print statements to check on the progress and success of different parts of my code, but XCODE fills in thousands of lines of excess info in seconds that quickly cover up my specific statements.

What I want to do:

print("Hello world!")
//Psuedo code:
Extension print(text: String) {
    let newText = "*\(text)"
    return newText
}

Output: *Hello World!

I will then filter the Xcode debugging output for asterisks. I have been doing this manually

Upvotes: 21

Views: 14587

Answers (3)

Code Different
Code Different

Reputation: 93151

You can overshadow the print method from the standard library:

public func print(items: Any..., separator: String = " ", terminator: String = "\n") {
    let output = items.map { "*\($0)" }.joined(separator: separator)
    Swift.print(output, terminator: terminator)
}

Since the original function is in the standard library, its fully qualified name is Swift.print

Upvotes: 31

PiterPan
PiterPan

Reputation: 1802

If we want to cover all cases with custom print we should create new file for example: CustomPrint.swift and then paste this two methods:

SWIFT 5.1

First (according to ThomasHaz answer)

public func print(_ items: String..., filename: String = #file, function : String = #function, line: Int = #line, separator: String = " ", terminator: String = "\n") {
    #if DEBUG
        let pretty = "\(URL(fileURLWithPath: filename).lastPathComponent) [#\(line)] \(function)\n\t-> "
        let output = items.map { "\($0)" }.joined(separator: separator)
        Swift.print(pretty+output, terminator: terminator)
    #else
        Swift.print("RELEASE MODE")
    #endif
}

and second because the first one does't cover dictionary and array printing

public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    #if DEBUG
        let output = items.map { "\($0)" }.joined(separator: separator)
        Swift.print(output, terminator: terminator)
    #else
        Swift.print("RELEASE MODE")
    #endif
}

Enjoy :)

Upvotes: 23

Nehrulal Hingwe
Nehrulal Hingwe

Reputation: 326

This code working for me in swift 3

import Foundation

public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    let output = items.map { "\($0)" }.joined(separator: separator)
    Swift.print(output, terminator: terminator)
}

class YourViewController: UIViewController {
}

Upvotes: 20

Related Questions