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
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.
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 .
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.
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
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 {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With