Make Xcode (swift )throw error for print() - xcode

I created a custom Logger for logging values for different modes like debug, release but I want that whenever I use the default print() Xcode should throw an error explaining the user to use the custom logger.
I referred this but want to throw error there and then rather than adding a build-phase.
Any Ideas ?

You could shadow the built-in print in your module and mark it "unavailable":
// swift 3:
#available(*, unavailable, message: "use Logger instead!")
internal func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
Swift.print(items, separator: separator, terminator: terminator)
}
// swift 2:
#available(*, unavailable, message="use Logger instead!")
internal func print(items: Any..., separator: String = " ", terminator: String = "\n") {
Swift.print(items, separator: separator, terminator: terminator)
}
The result looks like:
(There is still another instance of print<Target>(..., to output: inout Target) which I don't bother to hide, I guess no one will accidentally use that function.)
As shown, you could still use the qualified name Swift.print to refer to the real function in case of emergency.
Note that this will only affect your own module. You can't force users outside of your module to not use print.

Related

Is there a way to use the fmt.Scan() function with a message in one line?

Is there is a way to get an input from the user with a message in one line, like in python where you would do name = input("Name: ") instead of doing:
var name string
fmt.Println("Name: ")
fmt.Scan(&name)

Why does an error occur when I try to test if a member variable (string) in a class is empty?

I'm working on a project and need to test one of my class' member variables to verify that the user did indeed enter a string.
I've also tried using (patronName == '') and (patronName == "") but have had no luck.
Edit: Using "\n" fixes the error but the program ends without allowing the user to enter a name.
std::string Restaurant::getPatronName()
{
bool controlFlag = true;
do
{
getline(std::cin,patronName);
if ((std::cin.fail()) || (patronName == '\n'))
{
std::cout << "You must enter a name!" << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
else
{
controlFlag = false;
}
} while (controlFlag);
return patronName;
}
The function should read and store the name entered by the user into patronName. When trying to build, I get an error that says "no match for 'operator=='". Could this be because the object called in main is a pointer of type Restaurant?
Besides the type mismatch between the character '\n' and the std::string patronName, we can find at https://en.cppreference.com/w/cpp/string/basic_string/getline that std::getline(input, str, delim);
Extracts characters from input and appends them to str until […] the next available input character is delim, […], in which case the delimiter character is extracted from input, but is not appended to str.
So there won't be any '\n' character, if delim is the newline, in the first place.
You can use std::basic_string::empty() to check if a string is empty.
What happens with '\n' is you are comparing a string with a char, which, i suspect, there is no operator== defined for this case. If you are sure the string isn't empty, you can call operator[] formerName[0], which returns a char.
You have to write patronName == "\n" because you cannot compare string and character

How do I print a custom description of a Swift struct while debugging, and nothing else?

Say I have a struct like this one:
struct MyStruct: CustomStringConvertible {
let myInt: Int
let myString: String
var description: String {
return "my int is \(myInt),\nand my string is \"\(myString)\""
}
}
Printing a description from the code works fine.
let myStruct = MyStruct(myInt: 3, myString: "hello")
print(myStruct)
This results in
my int is 3,
and my string is "hello"
Problems arise when I want to print myStruct's description from the debugger. po myStruct results in
▿ my int is 3,
and my string is "hello"
- myInt : 3
- myString : "hello"
Explicitly printing out its description doesn't help either, as po myStruct.description results in
"my int is 3,\nand my string is \"hello\""
I thought it might have to do with CustomDebugStringConvertible, so I added this code:
extension MyStruct: CustomDebugStringConvertible {
var debugDescription: String {
return description
}
}
Unfortunately, this doesn't change any of the outcomes at all.
Is there a way to just have
my int is 3,
and my string is "hello"
printed from the command line while debugging?
(lldb) expression print(myStruct)
my int is 3,
and my string is "hello"
you can defined your own 'command'
(lldb) help command
The following subcommands are supported:
alias -- Allow users to define their own debugger command
abbreviations. This command takes 'raw' input (no need to
quote stuff).
delete -- Allow the user to delete user-defined regular expression,
python or multi-word commands.
history -- Dump the history of commands in this session.
regex -- Allow the user to create a regular expression command.
script -- A set of commands for managing or customizing script commands.
source -- Read in debugger commands from the file <filename> and execute
them.
unalias -- Allow the user to remove/delete a user-defined command
abbreviation.

Logging in Swift 2.0

I am new to XCode and work on Android Studio previously. In Android Studio, there is log cat to log different types of messages for debugging purposes.
Is this available in XCode?
All I found is NSLog which prints the date and the statement without coloring like in log cat. Is there an easier way ?
You can use the print method.
Check out these handy Apple docs.
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
using XCodeColors Library https://github.com/robbiehanson/XcodeColors you can log different types of messages each in a unique color so that you can find error logs faster
also i customized the code like this to get coloring, which class, function, and line number did the call
struct RZLog
{
static let ESCAPE = "\u{001b}["
static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color
static let RESET_BG = ESCAPE + "bg;" // Clear any background color
static let RESET = ESCAPE + ";" // Clear any foreground or background color
static let A = "fg255,0,0;"
static let B = "fg0,0,255;"
static let C = "fg16,128,0;"
static func Error<T>(object: T, filename: String = FILE, line: Int = LINE, funcname: String = FUNCTION) {
let ClassName = NSURL(string: filename)!
print("\(ESCAPE)\(A)**ERROR \(ClassName.lastPathComponent!)(\(line)) Func: \(funcname.uppercaseString): \(object) **\(RESET)")
}
static func Debug<T>(object: T, filename: String = FILE, line: Int = LINE, funcname: String = FUNCTION) {
let ClassName = NSURL(string: filename)!
print("\(ESCAPE)\(B)**DEBUG \(ClassName.lastPathComponent!)(\(line)) Func: \(funcname.uppercaseString): \(object) **\(RESET)")
}
static func VIP<T>(object: T, filename: String = FILE, line: Int = LINE, funcname: String = FUNCTION) {
let ClassName = NSURL(string: filename)!
print("\(ESCAPE)\(C)**VIP \(ClassName.lastPathComponent!)(\(line)) Func: \(funcname.uppercaseString): \(object) **\(RESET)")
}
}
If you want to use different CocoaLumberjack:
https://github.com/CocoaLumberjack/CocoaLumberjack
Which provides some more advantages over simple logging. And it can also be used with colors:
http://code.tutsplus.com/tutorials/cocoalumberjack-logging-on-steroids--mobile-15287
You can use Printer a new logging experience in Swift 3.x.
It has many functions to add logs in various ways.
Usage:
To log a success message:
Printer.log.success(details: "This is a Success message.")
Output:
Printer ➞ [✅ Success] [⌚04-27-2017 10:53:28] ➞ ✹✹This is a Success message.✹✹
[Trace] ➞ ViewController.swift ➞ viewDidLoad() #58
Disclaimer: This library has been created by me.

New syntax for default values in Swift functions

I just noticed that the latest beta of Xcode (7.1) has changed the signature for the print function in Swift.
The new syntax is:
public func print(items: Any..., separator: String = default, terminator: String = default)
Anybody knows what this default thing is? How do you specify the default value, not just the fact that it has one?
The default in the function signature means that it has a default value and you don't have to pass a parameter.
func add(a: Int = 0, b: Int = 0) -> Int {
return a + b
}
// "normal" function call
add(2, b: 4) // 6
// no specified parameters at all
add() // 0; both a and b default to 0
// one parameter specified
// a has no external name since it is the first parameter
add(3) // 3; b defaults to 0
// b has an external name since it is not the first parameter
add(b: 4) // 4; a defaults to 0
In case of the print function separator defaults to " " and terminator to "\n".
There are 4 way to call it:
struct SomeItem {}
print(SomeItem(), SomeItem())
print(SomeItem(), SomeItem(), separator: "_")
print(SomeItem(), SomeItem(), terminator: " :) \n")
print(SomeItem(), SomeItem(), separator: "_", terminator: " :) \n")
Prints:
SomeItem() SomeItem()
SomeItem()_SomeItem()
SomeItem() SomeItem() :)
SomeItem()_SomeItem() :)
the default separator is a single space, and the default terminator is a newline
to use a different value for either of these, simply pass the desired value as an argument when you call the function - e.g.:
print("first", "second", separator: "-", terminator: "...")
print("third")
// => "first-second...third"

Resources