I have this line:
randomIndex = Int(drand48() % Double(alphabetColors.count))
And Xcode 8 (Swift 3) tells me:
'%' is unavailable: Use truncatingRemainder instead
Is there no operator anymore? How should I convert my code?
You can simply follow the diagnostic message:
let randomIndex = Int(drand48().truncatingRemainder(dividingBy: Double(alphabetColors.count)))
Or using arc4random_uniform(_:) would be a better alternative.
let randomIndex = Int(arc4random_uniform(UInt32(alphabetColors.count)))
This seems to be available for me, currently on Swift 3.1, so possible it was added back.
My guess is that it's somewhere in Foundation and needs an explicit import Foundation
Update
This is for Int types only. It seems that for doubles, truncating remainder is required.
Cast your variable to Int before mod
example
let result = Int(value) % 3
As per new Guideline Swift 5, it's changed
value.truncatingRemainder(dividingBy: 2)
Use https://developer.apple.com/documentation/swift/double/2884269-remainder
If you use truncatingRemainder (as mentioned in the other comments) then it is going to floor the value first, which means 3.14 is going to become 3.
You can use this code to find the modulus of 2 numbers.
label.text is to display the result in a label that I have already designed
let result = Int(num1) % Int(num2)
label.text = String(Int(result))
Related
I've been reading the Apple Developer Documentation and it appears that it's not updated for the class NumberFormatter, they say it swapped from NSNumberFormatter to just NumberFormatter.
I've found a few examples of functionalities of this class in Swift 3 but I couldn't find how to set the maximumFractionDigits.
When I have a Double like this 0.123456789, I'd like to convert it into a String with just 4 fractional digits for example, like this 0.1234.
If you don't want it to round up, but rather always round down, use .floor or .down:
let foo = 0.123456789
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 4
formatter.roundingMode = .down
let string = formatter.string(from: NSNumber(value: foo))
If you want the traditional rounding format, just omit the .roundingMode, and this will result in "0.1235".
For more information, see the NumberFormatter reference documentation.
val = 345.09874
now i want output like 345.10, 345.09 and 345.099 in python 2.7
Please help me.
Just to encourage you I am providing the answer, but next time you should google first.
Use this:
print round(val,2)
I could get 2 out of 3 values using:
val = 345.09874
print("%.2f" % round(val,2)) #345.10
print("%.3f" % round(val,3)) #345.099
I dont know how to get the output with 345.09
I am converting a CoreText based app to Swift and I am facing an issue when getting the matches to a regular expression in the text.
This is the sample code
let regexOptions = NSRegularExpressionOptions.CaseInsensitive | NSRegularExpressionOptions.DotMatchesLineSeparators
let regex = NSRegularExpression.regularExpressionWithPattern("(.*?)(<[^>]+>|\\Z)", options: regexOptions, error: nil)
var results: Array<NSTextCheckingResult> = regex.matchesInString(text, options: 0, range: NSMakeRange(0, countElements(text)))
According to the documentation, the matchesInString function returns an array of NSTextCheckingResults, but the compiler complains stating that "The Expression of type anyObject[] can´t be converted to "NSMatchingOptions". Any idea of what might be wrong here?
Try assigning to your results variable like this:
var results = regex.matchesInString(text, options: nil, range: NSMakeRange(0, countElements(text))) as Array<NSTextCheckingResult>
the return type is Array<AnyObject>[]!, you can cast here (as in the above example) or later when you check the members of the collection
in Swift options take nil to represent an empty option set (vs. 0 in Objective-C)
I just sat with a problem related to some regexes and thought I would add a warning to the answer submitted above. My regexes matches seemed to be cut short and it turned out that the range i supplied was incorrect. I generated the range in the way described by #fqdn. It turned out that my strings contained carriage returns (\u{A}) and that these were not counted by the countElements function.
I countered this by calling .unicodeScalars on the string which seems to correctify the lenght.
println(countElements("\u{A}\u{A}\u{A}\n\u{D}\n\u{D}\n\u{D}\n\u{D}\n")) //8
println(countElements("\u{A}\u{A}\u{A}\n\u{D}\n\u{D}\n\u{D}\n\u{D}\n".unicodeScalars)) //12
Disclaimer: This is quite probably a swift-bug and might get fixed in a later version.
I need to parse input text file as custom language that i should interpret it's commands (line by line) and execute it, that's the input i should expect:
#Some variables
myInt = 2
myFloat = 2.5
myString = “Hello”
#Lists
myList = (myInt, myFloat, myInt + myFloat)
myOtherList = (myFloat + myFloat, myInt+ myInt)
subList = myList[:1]
completeList = myList + myOtherList + subList
#This should have no effect (it is ok if it is being calculated)
2+4
#Now some printing
print(myString)
print(“World”)
print(completeList)
print(completeList[3])
#Some syntax errors
b = “hello, this string is not enclosed right
c = myString + completeList
d = myInt + SOME_VARIABLE_I_HAVENT_DEFINED_YET
#First string to appear makes everything a string
print(1 + 2 + 15.5 + 2.2 + “Hi” + 3 + 4 + 6)
print(1 + 2 + 15.5 + 2.2 + 3 + 4 + 6 + “hi”)
print((1,2))
So I already have a first checking function, now I know when it's print/assign/comment/bad syntax command or whatever. I now should parse what inside the print function and the assign commands, I should ignore white spaces, they also might not be as delimiters to count on.
Please guide me a bit, what string functions i should use and how in order to to make it work, I mean how you can cut to tokens and also identify the mathematical signs? I'm guessing it should use some stack to follow the parentheses of the list type and quotation signs, no? Any general and more detailed information will be appreciated, thanks(:
p.s.
That's the output for this code:
Hello
World
(2, 2.5, 4.5, 5.0, 4, 2, 2.5)
5.0
InvalidSyntax : b = “hello, this string is not enclosed right
InvalidSyntax : c = myString + completeList
UndefinedVariableName : SOME_VARIABLE_I_HAVENT_DEFINED_YET
20.7Hi346
33.7hi
(1,2)
I already have all the overloading operators for what I need, I only need to parse it right and send it to my already built functions.
So you haven't had a chance to read the Dragon Book...
How do you think about embedding Lua or Python interpreter into your product, instead of inventing your own language? They are more common and full-fledged programming languages. Moreover Google will help you find lots of tutorials on how to embed them, such as:
http://docs.python.org/extending/embedding.html
http://www.ibm.com/developerworks/linux/library/l-embed-lua/
The disadvantage of inventing your own language is that: even after you successfully parsed your own language, you need to define semantics for it. Parsing only deals with the syntax, which is a different thing from the semantics. I don't know your situation but both of them usually require too long time to learn for just a single software project.
As for Boost Spirit: I don't recommend to use it which was written by people who just wanted to show their smartness by writing it (but in the end showed their ignorance about what is practical software design.)
A wonderful C++ library exists for that : SPIRIT
Is there default(in SDK) scala support for string templating? Example: "$firstName $lastName"(named not numbered parameters) or even constructs like for/if. If there is no such default engine, what is the best scala library to accomplish this.
If you want a templating engine, I suggest you have a look at scalate. If you just need string interpolation, "%s %s".format(firstName, lastName) is your friend.
Complementing Kim's answer, note that Java's Formatter accepts positional parameters. For example:
"%2$s %1$s".format(firstName, lastName)
Also, there's the Enhanced Strings plugin, which allows one to embed arbitrary expressions on Strings. For example:
#EnhanceStrings // enhance strings in this scope
trait Example1 {
val x = 5
val str = "Inner string arithmetics: #{{ x * x + 12 }}"
}
See also this question for more answers, as this is really a close duplicate.
In Scala 2.10 and up, you can use string interpolation
val name = "James"
println(s"Hello, $name") // Hello, James
val height = 1.9d
println(f"$name%s is $height%2.2f meters tall") // James is 1.90 meters tall
This compiler plug-in has provided string interpolation for a while:
http://jrudolph.github.com/scala-enhanced-strings/Overview.scala.html
More recently, the feature seems to be making it into the scala trunk: https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/test/files/run/stringInterpolation.scala -- which generates some interesting possiblities: https://gist.github.com/a69d8ffbfe9f42e65fbf (not sure if these were possible with the plug-in; I doubt it).