What does backslash do in Swift? - swift

In the following line of code, what is the backslash telling Swift to do?
print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")

The backslash has a few different meanings in Swift, depending on the context. In your case, it means string interpolation:
print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")
...is the same as:
print("The total cost of my meal is " + String(dictionary["pizza"]! + dictionary["ice cream"]!))
But the first form is more readable. Another example:
print("Hello \(person.firstName). You are \(person.age) years old")
Which may print something like Hello John. You are 42 years old. Much clearer than:
print("Hello " + person.firstName + ". You are " + String(person.age) + " years old")

That's called String interpolation. When you want to embed the value of a variable in a String, you have to put the variable name between parentheses and escape the opening parentheses with a backslash. This way the compiler knows that it has to substitute the value of the variable there instead of using the String literal of the variable name.
For more information on the topic, have a look at the String interpolation part of the Swift Language Guide.

Related

How do I use a string (str) and an integer (int) in the same line of code?

Whenever I try to run this code, I get an error about str() and int():
current_year = input ("What year is it?")
current_year = int(current_year)
birth_year = input ("What year were you born in?")
birth_year = int(birth_year)
print ("You are") + (current_year - birth_year) + ("years old.")
How can I get this code to work?
Any help would be greatly appreciated!
Try casting your integers to strings with python's built-in str() method then just add the appropriate string concatenations like so:
print("You are " + str(current_year - birth_year) + " years old.")
Hopefully that helps!
Add str(number) to your print statement.
print ("You are " + str(current_year - birth_year) + " years old.")
Nick I see you are a 11 yo entrant - keep up the enthusiasm and come here to us for answers, but do your HW first.
Strings str() are basically long texts. So if you want to concatenate (join back to back) with other texts, you have to first convert the numbers into text. Hence str (1972 -1960) will give you 12 as a text string. Once it is in that form, mathematical operations on it will return an error or null, but str(current_year - birth_year) + " years old." will give you " 12 years old." - with a 'space' factored in.

Returning the string between the 5th and 6th Spaces in a String

I have a column of strings that look like this:
Target Host: dcmxxxxxxc032.erc.nam.fm.com Target Name:
dxxxxxxgsc047.erc.nam.fm.com Filesystem /u01 has 4.98% available space
- fallen below warning (20) or critical (5) threshold.
The column name is [Description]
The substring I would like returned is (dxxxxxxgsc047.erc.nam.fm.com)
The only consistency in this data is that the desired string occurs between the 5th and 6th occurrences of spaces " " in the string, and after the phrase "Target Name: " The length of the substring varies, but it always ends in another " ", hence my attempt to grab the substring between the 5th and 6th spaces.
I have tried
MID([Description],((FIND([Description],"Target Name: "))+13),FIND([Description]," ",((FIND([Description],"Target Name"))+14)))
But that does not work.
(Edit: We use Tableau 8.2, the Tableau 9 only functions can't be part of the solution, thanks though!)
Thank you in advance for your help.
In Tableau 9 you can use regular expressions in formulas, it makes the task simpler:
REGEXP_EXTRACT([Description], "Target Name: (.*?) ")
Alternatively in Tableau 9 you can use the new FINDNTH function:
MID(
[Description],
FINDNTH([Description]," ", 5) + 1,
FINDNTH([Description]," ", 6) - FINDNTH([Description]," ", 5) - 1
)
Prior to Tableau 9 you'd have to use string manipulation methods similar to what you've tried, just need to be very careful with arithmetic and providing the right arguments (the third argument in MID is length, not index of the end character, so we need to subtract the index of the start character):
MID(
[Description]
, FIND([Description], "Target Name:") + 13
, FIND([Description], " ", FIND([Description], "Target Name:") + 15)
- (FIND([Description], "Target Name:") + 13)
)
Well, you need to find "Target name: " and then the " " after it, not so hard. I'll split in 3 fields just to be more clear (you can mix everything in a single field). BTW, you were in the right direction, but the last field on MID() should be the string length, not the char position
[start]:
FIND([Description],"Target name: ")+13
[end]:
FIND([Description]," ",[start])
And finally what you need:
MID([Description],[start]+1,[end]-[start]-1)
This should do. If you want to pursue the 5th and 6th " " approach, I would recommend you to find each of the " " until the 6th.
[1st]:
FIND([Description], " ")
[2nd]:
FIND([Description], " ",[1st] + 1)
And so on. Then:
MID([Description],[5th]+1,[6th]-[5th]-1)
A simple solution -
SPLIT( [Description], " ", 3 )
This returns a substring from the Description string, using the space delimiter character to divide the string into a sequence of tokens.
The string is interpreted as an alternating sequence of delimiters and
tokens. So for the string abc-defgh-i-jkl, where the delimiter
character is ‘-‘, the tokens are abc, defgh, i and jlk. Think of these
as tokens 1 through 4. SPLIT returns the token corresponding to the
token number. When the token number is positive, tokens are counted
starting from the left end of the string; when the token number is
negative, tokens are counted starting from the right. -
Tableau String Functions
I don't know Tableau, but perhaps something like this?
MID(
MID([Description], FIND([Description],"Target Name: ") + 13, 50),
1,
FIND(MID([Description], FIND([Description],"Target Name: ") + 13, 50), " ")
)

coffeescript multiline strings compile into multiline strings

How come that this string
"answer
to life
the universe
and everything
is
#{40+2}
"
compiles into
" answer to life the universe and everything is " + (40 + 2) + "";
how can I force coffescript to keep it multiline (keeping string interpolation intact):
"answer \
to life \
the universe \
and everything \
is \
"+(40+2)
Try using the heredoc syntax:
myString = """
answer
to life
the universe
and everything
is
#{40+2}
"""
This converts to this javascript:
var myString;
myString = "answer\nto life\nthe universe\nand everything\nis\n" + (40 + 2);
There's not really any point to make it actually be on newlines in the compiled javascript visually, is there?
I agree it is nice to be able to keep your indentation when defining long strings. You can use string addition for this effect in coffeescript just like you can in javascript:
myVeryLongString = 'I can only fit fifty-nine characters into this string ' +
'without exceeding eighty characters on the line, so I use ' +
'string addition to make it a little nicer looking.'
evaluates to
'I can only fit fifty-nine characters into this string without exceeding eighty characters, so I use string addition to make it a little nicer looking.'

Scala new line without regex?

I am trying to insert a new line into a string in scala. I've been reading around and it seems to not be as straight forward as java or C++.
my problem is i have a class called usedCar and Im overriding the toString method which is a 1 liner.
override def toString = ("Make: " + _carMake + "\nYear of Car: " + _yearOfCar + "\nVin Number: " + _vinNumber + "\nOdometer Mileage: " + _odometerMileage + "\nCondition of Car: " + _carCondition + "\nBest Price: " + _bestPrice + "\nAsking Price: " + askingPrice);
if someone can tell me how to get new lines in that toString method I would greatly appreciate it.
The escape code in Java for a new line is \n.
In your original question before the edit you have /n which wasn't correct.
The idiomatic way to do this is to assign sys.props("line.separator") to a variable and append that instead.
A more modern idiomatic way to do this would be to use String.format() and build your String that way and supply the sys.props("line.separator") as well.
You're using the wrong kind of slash. You want a backslash (\n) not a forward slash (/n). The question has since been edited.
And if you are on Windows, you really want \r\n instead. There are better ways of deciding which one to use, as Jarrod mentions in his answer.

Format a variable in iReport in a string with multiple fields

I have a text field that has the following expression:
$F{casNo} + " Total " + $P{chosenUom} + ": " + $V{total_COUNT}
casNo is a string, chosenUom is a string. total_COUNT is a sum variable of doubles. The total_COUNT variable displays, but it's got 8 - 10 decimal places (1.34324255234), all I need is something along the lines of 1.34.
Here's what I tried already:
$F{casNo} + " Total " + $P{chosenUom} + ": " + new DecimalFormat("0.00").format($V{total_COUNT}).toString()
Any help would be appreciated
For now I'm just doing basic math, but I'm hoping for a real solution, not a workaround
((int)($V{total_COUNT}*100.0))/100.0
You can format the in lline numbers by using:
new DecimalFormat("###0.00").format(YOUR NUMBER)
You might split the text field into two, one containing everything but the $V{total_COUNT}, and the second containing only $V{total_COUNT}, but with the Pattern property set to something like "#0.00".
You'd have to get a bit creative with layout, though, to prevent unwanted word-wrapping and spacing; for example, first text field could be wide and right-aligned, while text field containing the count could be left-aligned and wide enough to accommodate the formatted number.