Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
806 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can overshadow the print method from the standard library:

public func print(items: Any..., separator: String = " ", terminator: String = "
") {
    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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...