Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 350
Alec O Avatar asked Aug 18 '16 20:08

Alec O


People also ask

Can we extend struct in Swift?

It is not possible to subclass a struct in Swift, only classes can be subclassed. An extension is not a subclass, it's just adding additional functionality on to the existing struct , this is comparable to a category in Objective-C.

What is the use of extension in Swift?

In Swift, we can add new functionality to existing types. We can achieve this using an extension. Here, we have created an extension of the Temperature class using the extension keyword. Now, inside the extension, we can add new functionality to Temperature .

What does print mean in Swift?

You use print() in Swift to print a string of text to the Console, or standard output. It's super useful for debugging and finding out what's going on in your code. In this tutorial, we'll discuss how you can customize print() to code more productively.


2 Answers

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

like image 179
Code Different Avatar answered Nov 16 '22 00:11

Code Different


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 {
}
like image 21
Nehrulal Hingwe Avatar answered Nov 16 '22 01:11

Nehrulal Hingwe