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

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

xcode - 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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...