0

My point is to extend Swift.print() function or writing my own custom function ns_print() which could be available from all modules without explicit import.

Of cause I saw some answers like

public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
    let output = items.map { "\($0)" }.joined(separator: separator)
    Swift.print(output, terminator: terminator)
}

But it works only inside module it was defined. I want to share this function across all existing modules.

Is it possible? Any help?

ailinykh
  • 73
  • 1
  • 5
  • If you are using modules, then you will just have to declare it in a common module and import that common module everywhere else, to use your custom print function. – Shamas S Feb 28 '18 at 09:26
  • You can put in global to access everywhere – Jaydeep Vora Feb 28 '18 at 09:27
  • Possible duplicate of [Swift: Extending functionality of print() function](https://stackoverflow.com/questions/39026752/swift-extending-functionality-of-print-function) – heyfrank Feb 28 '18 at 09:28
  • Can you explain why you want to override the functionality of `print`? It might help people to suggest alternative approaches – JeremyP Feb 28 '18 at 09:44
  • I need to log all prints output into special file on macOS app – ailinykh Feb 28 '18 at 09:46
  • 1
    @ailinykh: In that case you can *redirect* standard output to a file, compare https://stackoverflow.com/questions/41680004/redirect-nslog-to-file-in-swift-not-working. – Martin R Feb 28 '18 at 10:01

1 Answers1

3

Nope, it's not possible, if you want to use a function from a different module, you have to import that module.

The default print function is part of the Swift module, which is automatically (implicitly) imported in all Swift files, this is why it's available everywhere without explicitly importing the module.

Cristik
  • 30,989
  • 25
  • 91
  • 127