func showNumbers(){
if let inputString = numberInput.text {
let input = Int(inputString)
let nums = input?.formattedWithSeparator
let group = Int(round(groupslider.value))
let priceEach = Int(round(Double((nums)!/group*100))/100)
perperson.text = String(priceEach)
}
}
}
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = " "
formatter.numberStyle = .decimal
return formatter
}()
}
extension BinaryInteger {
var formattedWithSeparator: String {
return Formatter.withSeparator.string(for: self) ?? ""
}
}
I have two places that I want to make it like 1,000,000
input String and perperson.text
what should I use? NSNumberForatter?
I want to use thousandSeparator or groupSeparator.
I get " Binary operator '/' cannot be applied to operands of type 'String' and 'Int' " this error message.
Related
I am trying to compare string data taken off a Persistant Vector, with an if statement. However, the comparison is not working, it always evaluates to false in the if. The code is below with the comment, //trying to compare strings
export function removeStudent(rmstudidx: i32): string{
let ablist = new Array<string>();
let rmstudent: string = "";
let abstudent: string = "";
let abindx = new Array<i32>();
let absentidx: i32;
let x: i32 = 0;
abstudent = studentlist[rmstudidx];
if(studentlist.containsIndex(rmstudidx)){
rmstudent = studentlist.swap_remove(rmstudidx);
//return "Removed " + rmstudent;
}
while (x < absentlist.length){
abstudent = studentlist[rmstudidx];
if(rmstudent === abstudent){ //trying to compare strings
return "In the string test"
absentlist.swap_remove(x);
x++;
}
}
return "Removed " + rmstudent;
}
In your line, where you write
if(rmstudent === abstudent){
You are writing ===, which is not the same as === in JavaScript.
AssemblyScript is strict, and using === will check if the objects are the same. If you want to do string comparison, you should use == instead.
Here's an example from the documentation of AssemblyScript
var a = "hello"
var b = a
var c = "h" + a.substring(1)
if (a === b) { /* true */ }
if (a === c) { /* false */ }
if (a == c) { /* true */ }
I want to create a signature for the myJD REST-API. But the first snippet is not working. I talked to the support and they told me that I need the unhexed key to create the correct hash. So I created a Byte-Array of the Hex-Value and changed the code to work again (see second snippet). Both methods have the same result.
Link to API documentation: https://docs.google.com/document/d/1IGeAwg8bQyaCTeTl_WyjLyBPh4NBOayO0_MAmvP5Mu4/edit?pref=2&pli=1
First:
import Foundation
extension String{
func hmacSHA256(key: String) -> String {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = Int(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding)!
let keyLen = Int(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), keyStr, keyLen, str!, strLen, result)
let digest = stringFromResult(result, length: digestLen)
result.dealloc(digestLen)
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
let hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
Second:
func hmacSHA256_2(key: String) -> String {
//let cKey = key.dataUsingEncoding(NSUTF8StringEncoding)!
let bKey = Array(key.utf8)
let bData = Array(self.utf8)
//let cData = self.dataUsingEncoding(NSUTF8StringEncoding)!
var cHMAC = [CUnsignedChar](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), bKey, Int(bKey.count), bData, Int(bData.count), &cHMAC)
let output = NSMutableString(capacity: Int(CC_SHA256_DIGEST_LENGTH))
for byte in cHMAC {
output.appendFormat("%02hhx", byte)
}
return output as String
}
Until Swift 2 I used this extension to remove multiple whitespaces:
func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty($0)})
return " ".join(components)
}
but with Swift 2 now I get the error
Cannot invoke 'isEmpty' with an argument list of type '(String)'
How could I now remove multiple spaces with Swift 2?
Thnx!
In Swift 2, join has become joinWithSeparator and you call it on the array.
In filter, isEmpty should be called on the current iteration item $0.
To replace whitespaces and newline characters with unique space characters as in your question:
extension String {
func condenseWhitespace() -> String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}
let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"
Because your function does not take any parameter you could make it a property instead:
extension String {
var condensedWhitespace: String {
let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
}
}
let result = "Hello World.\nHello!".condensedWhitespace // "Hello World. Hello!"
In Swift 3 there's even more changes.
Function:
extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
let result = "Hello World.\nHello!".condenseWhitespace()
Property:
extension String {
var condensedWhitespace: String {
let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
let result = "Hello World.\nHello!".condensedWhitespace
In Swift 4.2 NSCharacterSet is now CharacterSet, and you can omit and use dot syntax:
extension String {
func condenseWhitespace() -> String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
let result = "Hello World.\nHello!".condenseWhitespace() // "Hello World. Hello!"
Split string to array and then join again in not memory efficient. Its Takes lot of memory. The best way in this case is to scan the given string and perform operations on that. Regular Expression is the advance way to scan a text. For the above conclusion the the solution is given below:
Swift 4.x
extension String {
func removeExtraSpaces() -> String {
return self.replacingOccurrences(of: "[\\s\n]+", with: " ", options: .regularExpression, range: nil)
}
}
Usages
let startingString = "hello world! \n\n I am here!"
let processedString = startingString.removeExtraSpaces()
print(processedString)
Output:
processedString => "hello world! I am here!"
You can Do more according to your own requirements but thing I am pointing out here is to use regular expressions with string rather then create arrays which will consume lot of memory.
Cleanest version. Documented, memory efficient, extremely easy to use.
extension String {
/// Returns a condensed string, with no extra whitespaces and no new lines.
var condensed: String {
return replacingOccurrences(of: "[\\s\n]+", with: " ", options: .regularExpression, range: nil)
}
/// Returns a condensed string, with no whitespaces at all and no new lines.
var extraCondensed: String {
return replacingOccurrences(of: "[\\s\n]+", with: "", options: .regularExpression, range: nil)
}
}
Usage:
let a = " Hello\n I am a string ".condensed
let b = " Hello\n I am a string ".extraCondensed
Output:
a: "Hello I am a string"
b: "HelloIamastring"
SWIFT 3: Cleaner version
extension String {
var condensedWhitespace: String {
let components = self.components(separatedBy: .whitespacesAndNewlines)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
}
Here is mine: How it's actually worked.
extension String {
func removeExtraSpaces() -> String {
var data = ""
var numberOfSpace = 0
let items = self.getComponents(separatedBy: " ")
for item in items{
if item == " "{
numberOfSpace = numberOfSpace + 1
}else{
numberOfSpace = 0
}
if numberOfSpace == 1 || numberOfSpace == 0 {
data = data + item
//data.append(item)
}
}
return data
}
}
Usages
var message = "What is the purpose of life?"
message = message.removeExtraSpaces()
print(message)
Output:
What is the purpose of life?
var str = "Hello World.\nHello!"
if let regex = try? NSRegularExpression(pattern: "\\s+", options:NSRegularExpression.Options.caseInsensitive)
{
str = regex.stringByReplacingMatches(in: str, options: [], range: NSMakeRange(0, str.count), withTemplate: " ")
}
I am running the following code:
var inventario = PFQuery(className:"InventarioObjetos")
inventario.getObjectInBackgroundWithId(toPassID) {
(inventario: PFObject?, error: NSError?) -> Void in
if error != nil {
NSLog("%#", error!)
} else {
inventario["Categoria"] = self.nuevoCategoria.text
inventario["Descripcion"] = self.nuevoDescripcion.text
inventario["Tamano"] = self.tamano.text
// Guarda la fecha de entrada
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "dd-MM-yyyy"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let d = dateStringFormatter.dateFromString(self.nuevoFechaDeEntrada.text)
inventario["FechaDeEntrada"] = d
}
}
And on the inventario["Tamano"] = self.tamano.text line, I get this error:
Cannot assign a value of type 'String!' to a value of type 'AnyObject?'
Just cast self.tamano.text to an AnyObject: inventario["Tamano"] = self.tamano.text as! AnyObject
try this:
inventario["Tamano"] = self.tamano.text? (as! AnyObject?) shouldn't need this
Actually I would add the "?" in all your conversions just in case the user left one empty or a check like
if let strTamano = self.tamano.text{
inventario["Tamano"] = strTamano
} else { println("error converting tamano") }
of course the println would popup a dialog or do something more useful to the final user.
this question is similar to Replace occurrences of NSNull in nested NSDictionary
In swift I am getting an error (I believe because of NSNull's) I don't really care if the NSNull becomes an empty string or a nil. I am just wanting to get the code to work.
I have a large data structure coming in from JSON as an NSDictionary. Then I am saving that to a temporary file. Here is the code:
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as! NSDictionary
let json = JSON(jsonResult)
if (json["errors"].array?.count > 0) {
println("could not load stuff")
} else {
println("retrieving the stuff")
let file = "file.txt"
let file_path = NSTemporaryDirectory() + file
let dict:NSDictionary = jsonResult
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
if dict.writeToFile(file_path, atomically: true) {
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
//--- need to handle the NSNull junk here
if let dict = readDict {
println("Temp file created, here are the contents: \(dict)")
} else {
println("!!!Failed to READ the dictionary data back from disk.")
}
}
else {
println("!!!Failed to WRITE the dictionary to disk.")
}
}
Here's an example of what jsonResult looks like
things = (
{
"one" = one;
two = "<null>";
"three" = three;
"four" = "<null>";
"five" = five;
"six" = "six-6";
seven = 7;
eight = eight;
nine = "<null>";
ten = "<null>";
eleven = "<null>";
"twelve" = "<null>";
},
UPDATE:
Problem: I have a very large amount of JSON (roughly 600kb as text) Within that JSON data there are nulls. The problem I was having is that when you NSJSONSerialization as NSDictionary, it converts the nulls into NSNull objects (it looks funky if you print this out because they appear as a string, this is wrong.
Solution: You need to have a "pruned" or "sanitized" dictionary. What this means is to throw out the key and value entirely. To do this, I added a sanitized_dict function. Here is the function:
func sanitize_dict(obj: AnyObject) -> AnyObject {
if obj.isKindOfClass(NSDictionary) {
var saveableObject = obj as! NSMutableDictionary
for (key, value) in obj as! NSDictionary {
if (value.isKindOfClass(NSNull)) {
//println("Removing NSNull for: \(key)")
saveableObject.removeObjectForKey(key)
}
if (value.isKindOfClass(NSArray)) {
let tmpArray: (AnyObject) = sanitize_dict(value as! NSArray)
saveableObject.setValue(tmpArray, forKey: key as! String)
}
if (value.isKindOfClass(NSDictionary)) {
let tmpDict: (AnyObject) = sanitize_dict(value as! NSDictionary)
saveableObject.setValue(tmpDict, forKey: key as! String)
}
}
return saveableObject
//--- because arrays are handled differently,
//--- you basically need to do the same thing, but for an array
//--- if the object is an array
} else if obj.isKindOfClass(NSArray) {
var saveableObject = [AnyObject]()
for (index, ele) in enumerate(obj as! NSArray) {
if (ele.isKindOfClass(NSNull)) {
// simply don't add element to saveableobject and we're good
}
if (ele.isKindOfClass(NSArray)) {
let tmpArray: (AnyObject) = sanitize_dict(ele as! NSArray)
saveableObject.append(tmpArray)
}
if (ele.isKindOfClass(NSDictionary)) {
let tmpDict: (AnyObject) = sanitize_dict(ele as! NSDictionary)
saveableObject.append(tmpDict)
}
}
return saveableObject
}
// this shouldn't happen, but makes code work
var saveableObject = [AnyObject]()
return saveableObject
}
So your other code needs to call that function, it should look something like this:
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as! NSDictionary
//--- right now jsonResult is not actual json, and actually has the NSNulls
//--- get that result into the sanitized function above
let saveableDict: (AnyObject) = self.sanitize_dict(jsonResult)
let json = JSON(saveableDict)
if (json["errors"].array?.count > 0) {
println("!!!Failed to load.")
} else {
println("Load json successful. Attempting to save file...")
//--- set up basic structure for reading/writing temp file
let file = "file.txt"
let file_path = NSTemporaryDirectory() + file
let dict:NSDictionary = jsonResult
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
if dict.writeToFile(file_path, atomically: true) {
let readDict:NSDictionary? = NSDictionary(contentsOfFile: file_path)
if let dict = readDict {
println("Temp file created, here are the contents: \(dict)")
} else {
println("!!!Failed to READ the dictionary data back from disk.")
}
}
else {
println("!!!Failed to WRITE the dictionary to disk.")
}
}
Hope this helps somebody out there with a big JSON dataset and nulls. It is all about that sanitize function!