是否可以扩展Swift功能的功能?我想在我的程序中的每个print()函数上添加一个字符,而不必创建一个全新的函数并重命名print()的每个实例。是否可以创建一个将'*'附加到每个打印实例上的扩展名?
这样做的目的是创建一种清除XCODE添加到调试器中的所有额外信息的方法。我使用print语句检查代码不同部分的进度和成功,但XCODE在几秒钟内填写了数千行超额信息,很快就掩盖了我的具体陈述。
我想做什么:
print("Hello world!")
//Sudo code:
Extension print(text: String) {
let newText = "*\(text)"
return newText
}
输出: * Hello World!
然后我将过滤星号的Xcode调试输出。我一直在手动这样做
答案 0 :(得分:18)
您可以在标准库中掩盖print
方法:
public func print(items: Any..., separator: String = " ", terminator: String = "\n") {
let output = items.map { "*\($0)" }.joinWithSeparator(separator)
Swift.print(output, terminator: terminator)
}
由于原始函数位于标准库中,因此其完全限定名称为Swift.print
答案 1 :(得分:14)
此代码在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 {
}
答案 2 :(得分:3)
如果我们要使用自定义print
涵盖所有情况,则应创建一个新文件,例如:CustomPrint.swift
,然后粘贴以下两种方法:
SWIFT 5.1
First (according to ThomasHaz answer)
public func print(_ items: String..., filename: String = #file, function : String = #function, line: Int = #line, separator: String = " ", terminator: String = "\n") {
#if DEBUG
let pretty = "\(URL(fileURLWithPath: filename).lastPathComponent) [#\(line)] \(function)\n\t-> "
let output = items.map { "\($0)" }.joined(separator: separator)
Swift.print(pretty+output, terminator: terminator)
#else
Swift.print("RELEASE MODE")
#endif
}
and second because the first one does't cover dictionary and array printing
public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
#if DEBUG
let output = items.map { "\($0)" }.joined(separator: separator)
Swift.print(output, terminator: terminator)
#else
Swift.print("RELEASE MODE")
#endif
}
享受:)