Swift:扩展 print() 函数的功能 [英] Swift: Extending functionality of print() function

查看:47
本文介绍了Swift:扩展 print() 函数的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以扩展 Swift 函数的功能?我想在我的程序中的每个 print() 函数上附加一个字符,而不必创建一个全新的函数并重命名 print() 的每个实例.是否可以创建一个扩展,将*"附加到每个打印实例上?

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?

这样做的目的是创建一种清除 XCODE 添加到调试器中的所有额外信息的方法.我正在使用打印语句来检查我的代码不同部分的进度和成功,但 XCODE 会在几秒钟内填充数千行多余的信息,这些信息很快就会掩盖我的特定语句.

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.

我想做什么:

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

输出:*世界你好!

然后我将过滤 Xcode 调试输出中的星号.我一直在手动执行此操作

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

推荐答案

您可以掩盖标准库中的 print 方法:

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)
}

由于原函数在标准库中,所以它的全限定名是Swift.print

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

这篇关于Swift:扩展 print() 函数的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆