Swift Print function formatting - swift

This article has this code here:
// flatMap
let flatCars = peopleArray.flatMap({ $0.cars })
print("Flatmap: \(flatCars)")
/*Result: Flatmap: ["i20", "Swift VXI", "Crita", "Swift VXI"]*/
What is going on in the print function. Why can it not just be this:
print("Flatmap: ", flatCars) //typed outside of IDE
Is "Flatmap: \(flatCars)" meant to be string formatting similar to javascript's template literals e.g "Flatmap: ${flatCars}" in Js?
Useful resources for better understanding would be great.

Yes, it is similar to ${} in javaScript, and it is called String Interpolation:
String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal.
You can find more detailed information in here: Swift Documentation
under the section "String Interpolation".

Related

How to use DPI systemVerilog to detect a substring match?

How do I use SystemVerilog DPI to check if some string contains another string? For example, strstr() in C can detect "str" is contained within "string".
Not sure what you mean by DPI systemverilog? If you want to use functions similar to C functions, then I would highly suggest the svlib library by Verilab. It provides string manipulation methods using the Str class
http://www.verilab.com/resources/svlib/
UVM has regexp string methods built in. It's widely supported and optimized.
You want "uvm_re_match()" to do exactly what you want.
https://dvteclipse.com/uvm-1.2_Public_API/summary-function-uvm_pkg.html#function_uvm_re_match

Does Scala's string building form ```s"$var1"``` have a name?

What is the name given to the way that I can create Strings in Scala like this?
val foo = "hello"
val bar = "world"
val s = s"$foo $bar" /// <-- Does this construct have a name?
I'm trying to find if Javascript has a similar way of building strings and I wasn't sure what to search for.
It's called string interpolation
ES6 has 'template strings', if you're using ES5 you're out of luck. Coffeescript has string interpolation that compiles to regular string concatenation.
I'd like to add that underscore.js has a nice templating function, though it's not exactly string interpolation.

Swift replacement for Objective-C macro

I busy rewriting an app in Swift and would like to convert the following macro to Swift code.
#define FLOG(format, ...) NSLog(#"%#.%# %#", [self class], NSStringFromSelector(_cmd), [NSString stringWithFormat:format, ##__VA_ARGS__])
How can I define this as a Swift function such that I can use if anywhere for debug logging purposes, or is there an alternate way to achieve the same thing?
The easiest way is probably to take advantage of string interpolation and use:
func FLOG(message:String, method:String = __FUNCTION__) {
println("\(method): \(message)")
}
Then you usage is similar to:
FLOG("Illegal value: \(value)")
Having the method argument default to __FUNCTION__ means that it will normally be replaced with the calling function name. Other automatic variables that you could use include __FILE__, __LINE__ and __COLUMN__. Unfortunately __PRETTY_FUNCTION__ is no longer available.
If you want more control over the formatting of the message than string interpolation allows, take a look at this question which demonstrates simplifying access to printf-style formatting in Swift, and would let you do:
FLOG("Illegal value: %x" % [value])
See also this post from Apple that addresses using __FILE__ and __LINE__ in assert
Apple's answer to the removal of macros and something new to replace them is that nothing like macros will be available in swift. The closest you can get is to replace #define with a global let variable.
Example: instead of #define CONSTANT 0 you can write let CONSTANT = 0
Whereas, if you want to pass arguments inside a macro, that feature will no longer be available as considered bad programming practice. What you can do instead is create a function.

Embedding XML (and other languages?) in Scala

I'm wondering how the scala.xml library is implemented, to get an Elem-instance out of XML.
So I can write:
val xml = {
<myxml>
Some wired text withoud "'s or code like
import x
x.func()
It's like a normal sting in triple-quotes.
</myxml>
}
xml.text
String =
"
Some text wired withoud "'s or code like
import x
x.func()
It's like a normal sting in triple-quotes.
"
A look at the source code doesn't gave me the insight, how this is achieved.
Is the "XML-detection" a (hard) scala language feature or is it an internal DSL? Because I would like to build my own things like this:
var x = LatexCode {
\sqrt{\frac{a}{b}}
}
x.toString
"\sqrt{\frac{a}{b}}"
or
var y = PythonCode {
>>> import something
>>> something.func()
}
y.toString
"""import something ..."""
y.execute // e.g. passed to python as python-script
or
object o extends PythonCode {
import x
x.y()
}
o.toString
"""import x...."""
I would like to avoid using such things like PythonCode { """import ...""" } as "DSL". And in scala, XML is magically transported to a scala.xml-Class; same with Symbol which I can get with val a = 'symoblname, but in the source code there's no clue how this is implemented.
How can I do something like that on myself, preferably as internal DSL?
XML is a scala language feature (*) - see the SLS, section 1.5.
I think that string interpolation is coming in 2.10, however, which would at least allow you to define your own DSL:
val someLatex = latex"""\sqrt{\frac{a}{b}}}"""
It's an experimental feature explained more fully in the SIP but has been additionally blogged about by the prolific Daniel Sobral. The point of this is (of course) that the correctness of the code in the String can be checked at compile time (well, to the extent possible in an untyped language :-) and your IDE can even help you write it (well, to the extent possible in an untyped language :-( )
(*) - We might expect this to change in the future given the many shortcomings of the implementation. My understanding is that a combination of string interpolation and anti-xml may yet be the one true way.
It's an XML literal, just like "foo" is a string literal, 42 is an integer literal, 12.34 is a floating point literal, 'foo is a symbol literal, (foo) => foo + 1 is a function literal and so on.
Scala has fewer literals than other languages (for example, it doesn't have array literals or regexp literals), but it does have XML literals.
Note that in Scala 2.10 string literals become vastly more powerful by allowing you to intercept and re-interpret them using StringContexts. These more powerful string literals would allow you to implement all of your snippets, including XML without separate language support. It is likely that XML literals will be removed in a future version of the language.

Cool class and method names wrapped in ``: class `This is a cool class` {}?

I just found some scala code which has a strange class name:
class `This is a cool class` {}
and method name:
def `cool method` = {}
We can use a sentence for a class or method name!
It's very cool and useful for unit-testing:
class UserTest {
def `user can be saved to db` {
// testing
}
}
But why we can do this? How to understand it?
This feature exists for the sake of interoperability. If Scala has a reserved word (with, for example), then you can still refer to code from other languages which use it as a method or variable or whatever, by using backticks.
Since there was no reason to forbid nearly arbitrary strings, you can use nearly arbitrary strings.
As #Rex Kerr answered, this feature is for interoperablility. For example,
To call a java method,
Thread.yield()
you need to write
Thread.`yield`()
since yield is a keyword in scala.
The Scala Language Specification:
There are three ways to form an identifier. First, an identifier can
start with a letter which can be followed by an arbitrary sequence of
letters and digits. This may be followed by underscore ‘_’ characters
and another string composed of either letters and digits or of
operator characters. Second, an identifier can start with an operator
character followed by an arbitrary sequence of operator characters.
The preceding two forms are called plain identifiers. Finally, an
identifier may also be formed by an arbitrary string between
back-quotes (host systems may impose some restrictions on which
strings are legal for identifiers). The identifier then is composed of
all characters excluding the backquotes themselves.
Strings wrapped in ` are valid identifiers in Scala, not only to class names and methods but to functions and variables, too.
To me it is just that the parser and the compiler were built in a way that enables that, so the Scala team implemented it.
I think that it can be cool for a coder to be able to give real names to functions instead of getThisIncredibleItem or get_this_other_item.
Thanks for your questions which learnt me something new in Scala!