Any way to override the swift built in print function including constant variables? (#line, #function etc) - swift

I want to be able to override the default Swift standard library print function and include the line number and function name. I have tried several methods such as
public func print(_ items: Any..., separator: String = \(#line), terminator: String = #function {
let output = items.map { "\(terminator) \(separator) -> \($0)" }.joined(separator: " ")
Swift.print(output, terminator: "\n")
}
This correctly prints out the function name of the calling method, however the line number is set to the line number of the print function. I therefore tried changing the separator type to Int and passing #line to it as its default value.
This results in an "ambiguous use of function" error, and changing the signature doesn't help either as the default implementation is called in preference to my function.
I have looked at extensions and even swizzling but neither of these seem fruitful in this instance.

So it seems that in my case a signature change does solve the issue. By being specific about the type passed to the items argument, my custom method is called.
public func print(_ items: String..., filename: String = #file, function : String = #function, line: Int = #line, separator: String = " ", terminator: String = "\n") {
let pretty = "\(URL(fileURLWithPath: filename).lastPathComponent) [#\(line)] \(function)\n\t-> "
let output = items.map { "\($0)" }.joined(separator: separator)
Swift.print(pretty+output, terminator: terminator)
}
Note that all the print statements I care about pass Strings. The default implementation is called otherwise:
print(1+1)
// 2
print("Hello, World!")
// ExampleVC.swift [#101] viewDidLoad()
// -> Hello, World!
print("Hello", "World", separator: ", ", terminator: "!\n")
// ExampleVC.swift [#101] viewDidLoad()
// -> Hello, World!

Related

Swift custom print() function ignores line break

I'm trying to make a logging function and everything worked fine until I found this.
This is how print function's interface defined.
public func print(_ items: Any..., separator: String = " ", terminator: String = "\n")
so if I print print("a\nb"), it prints
a
b
however if I print the same string with the function below
func pLog(_ items: Any...) {
print(items)
}
it prints
["a\nb"]
What am I missing?

Trim only trailing whitespace from end of string in Swift 3

Every example of trimming strings in Swift remove both leading and trailing whitespace, but how can only trailing whitespace be removed?
For example, if I have a string:
" example "
How can I end up with:
" example"
Every solution I've found shows trimmingCharacters(in: CharacterSet.whitespaces), but I want to retain the leading whitespace.
RegEx is a possibility, or a range can be derived to determine index of characters to remove, but I can't seem to find an elegant solution for this.
With regular expressions:
let string = " example "
let trimmed = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
print(">" + trimmed + "<")
// > example<
\s+ matches one or more whitespace characters, and $ matches
the end of the string.
In Swift 4 & Swift 5
This code will also remove trailing new lines.
It works based on a Character struct's method .isWhitespace
var trailingSpacesTrimmed: String {
var newString = self
while newString.last?.isWhitespace == true {
newString = String(newString.dropLast())
}
return newString
}
This short Swift 3 extension of string uses the .anchored and .backwards option of rangeOfCharacter and then calls itself recursively if it needs to loop. Because the compiler is expecting a CharacterSet as the parameter, you can just supply the static when calling, e.g. "1234 ".trailing(.whitespaces) will return "1234". (I've not done timings, but would expect faster than regex.)
extension String {
func trailingTrim(_ characterSet : CharacterSet) -> String {
if let range = rangeOfCharacter(from: characterSet, options: [.anchored, .backwards]) {
return self.substring(to: range.lowerBound).trailingTrim(characterSet)
}
return self
}
}
In Foundation you can get ranges of indices matching a regular expression. You can also replace subranges. Combining this, we get:
import Foundation
extension String {
func trimTrailingWhitespace() -> String {
if let trailingWs = self.range(of: "\\s+$", options: .regularExpression) {
return self.replacingCharacters(in: trailingWs, with: "")
} else {
return self
}
}
}
You can also have a mutating version of this:
import Foundation
extension String {
mutating func trimTrailingWhitespace() {
if let trailingWs = self.range(of: "\\s+$", options: .regularExpression) {
self.replaceSubrange(trailingWs, with: "")
}
}
}
If we match against \s* (as Martin R. did at first) we can skip the if let guard and force-unwrap the optional since there will always be a match. I think this is nicer since it's obviously safe, and remains safe if you change the regexp. I did not think about performance.
Handy String extension In Swift 4
extension String {
func trimmingTrailingSpaces() -> String {
var t = self
while t.hasSuffix(" ") {
t = "" + t.dropLast()
}
return t
}
mutating func trimmedTrailingSpaces() {
self = self.trimmingTrailingSpaces()
}
}
Swift 4
extension String {
var trimmingTrailingSpaces: String {
if let range = rangeOfCharacter(from: .whitespacesAndNewlines, options: [.anchored, .backwards]) {
return String(self[..<range.lowerBound]).trimmingTrailingSpaces
}
return self
}
}
Demosthese's answer is a useful solution to the problem, but it's not particularly efficient. This is an upgrade to their answer, extending StringProtocol instead, and utilizing Substring to remove the need for repeated copying.
extension StringProtocol {
#inline(__always)
var trailingSpacesTrimmed: Self.SubSequence {
var view = self[...]
while view.last?.isWhitespace == true {
view = view.dropLast()
}
return view
}
}
No need to create a new string when dropping from the end each time.
extension String {
func trimRight() -> String {
String(reversed().drop { $0.isWhitespace }.reversed())
}
}
This operates on the collection and only converts the result back into a string once.
It's a little bit hacky :D
let message = " example "
var trimmed = ("s" + message).trimmingCharacters(in: .whitespacesAndNewlines)
trimmed = trimmed.substring(from: trimmed.index(after: trimmed.startIndex))
Without regular expression there is not direct way to achieve that.Alternatively you can use the below function to achieve your required result :
func removeTrailingSpaces(with spaces : String) -> String{
var spaceCount = 0
for characters in spaces.characters{
if characters == " "{
print("Space Encountered")
spaceCount = spaceCount + 1
}else{
break;
}
}
var finalString = ""
let duplicateString = spaces.replacingOccurrences(of: " ", with: "")
while spaceCount != 0 {
finalString = finalString + " "
spaceCount = spaceCount - 1
}
return (finalString + duplicateString)
}
You can use this function by following way :-
let str = " Himanshu "
print(removeTrailingSpaces(with : str))
One line solution with Swift 4 & 5
As a beginner in Swift and iOS programming I really like #demosthese's solution above with the while loop as it's very easy to understand. However the example code seems longer than necessary. The following uses essentially the same logic but implements it as a single line while loop.
// Remove trailing spaces from myString
while myString.last == " " { myString = String(myString.dropLast()) }
This can also be written using the .isWhitespace property, as in #demosthese's solution, as follows:
while myString.last?.isWhitespace == true { myString = String(myString.dropLast()) }
This has the benefit (or disadvantage, depending on your point of view) that this removes all types of whitespace, not just spaces but (according to Apple docs) also including newlines, and specifically the following characters:
“\t” (U+0009 CHARACTER TABULATION)
“ “ (U+0020 SPACE)
U+2029 PARAGRAPH SEPARATOR
U+3000 IDEOGRAPHIC SPACE
Note: Even though .isWhitespace is a Boolean it can't be used directly in the while loop as it ends up being optional ? due to the chaining of the optional .last property, which returns nil if the String (or collection) is empty. The == true logic gets around this since nil != true.
I'd love to get some feedback on this, esp. in case anyone sees any issues or drawbacks with this simple single line approach.
Swift 5
extension String {
func trimTrailingWhiteSpace() -> String {
guard self.last == " " else { return self }
var tmp = self
repeat {
tmp = String(tmp.dropLast())
} while tmp.last == " "
return tmp
}
}

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

String index in Swift 2.0: How can I work around indexing a string?

I am trying to get the contents of a string:
var oldString = "hi this \t is my \t string"
oldString = String(oldString.componentsSeparatedByString("\t"))
print(oldString[1])
I get the ERROR : " 'subscript' is unavailable:cannot subscript String
with an Int..."
How would I access a string that is contained in another string?
The only way I have come up with is to get character by character using:
for index in content.characters.indices{
print(String(oldString[index]))
}
The code above results in:
h,
i,
t,
h,
..
I need:
hi this,
is my,
string
Thank you in advance!
You should read the error message and figure out where does the error message come from.
Your String(oldString.componentsSeparatedByString("\t")) gives you a String not [String].
What you need to do is assigning oldString.componentsSeparatedByString("\t") to an array:
let stringArray = oldString.componentsSeparatedByString("\t")
for str in stringArray {
print(str)
}
In swift you can extend any type and add overloads for different operations. In the example below we've created an extension that allows you to subscript String returning each word and get an array from your string.
Simply paste this into a playground to test:
extension String {
func array() -> [String] {
return self.componentsSeparatedByString("\t")
}
subscript (i: Int) -> String {
return self.componentsSeparatedByString("\t")[i]
}
}
Once you've added your extension, you can use it throughout your application like so:
var str = "hi this \t is my \t string"
print(str[0]) //prints hi this
for i in str.array() {
print(i)
}
prints:
hi this
is my
string
var oldString = "hi this \t is my \t string"
let stringArray = oldString.componentsSeparatedByString("\t")
//In case you also need the index while iterating
for (index, value) in stringArray.enumerate(){
print("index is \(index) and string is \(value)")
}
for str in stringArray{
print(str)
}
Output will be as follows
index is 0 and string is hi this
index is 1 and string is is my
index is 2 and string is string
hi this
is my
string

How to create String split extension with regex in Swift?

I wrote extension that create split method:
extension String {
func split(splitter: String) -> Array<String> {
return self.componentsSeparatedByString(splitter)
}
}
So in playground I can write:
var str = "Hello, playground"
if str.split(",").count > 1{
var out = str.split(",")[0]
println("output: \(out)") // output: Hello
}
What do I need to make it work with regex like in Java:
str.split("[ ]+")
Because this way it doesn't work.
Thanks,
First, your split function has some redundancy. It is enough to return
return self.componentsSeparatedByString(splitter)
Second, to work with a regular expression you just have to create a NSRegularExpression and then perhaps replace all occurrences with your own "stop string" and finally separate using that. E.g.
extension String {
func split(regex pattern: String) -> [String] {
let template = "-|*~~*~~*|-" /// Any string that isn't contained in the original string (self).
let regex = try? NSRegularExpression(pattern: pattern)
let modifiedString = regex?.stringByReplacingMatches(
in: self,
range: NSRange(
location: 0,
length: count
),
withTemplate: template /// Replace with the template/stop string.
)
/// Split by the replaced string.
return modifiedString?.components(separatedBy: template) ?? []
}
}