Swift: Extending functionality of print() function

前端 未结 3 747
甜味超标
甜味超标 2020-12-09 05:01

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 br

相关标签:
3条回答
  • 2020-12-09 05:15

    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

    0 讨论(0)
  • 2020-12-09 05:26

    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 {
    }
    
    0 讨论(0)
  • 2020-12-09 05:28

    If we want to cover all cases with custom print we should create new file for example: CustomPrint.swift and then paste this two methods:

    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
    }
    

    Enjoy :)

    0 讨论(0)
提交回复
热议问题