I am stuck at a piece of code where I need to get the expression result based on the passed dictionary. For example:
expressionString = "(val1 + val2)"
How it is possible to pass these values from an dictionary or somewhere else. I searched many places but does't work for me.
let expressionString : String = "(val1 + val2)" as String
let expression = NSExpression(format: expressionString)
In above case I would like to know how I can map these val1 and val2 data by passing any argument.
Is it can be achieve by let ex = NSExpression(format: expressionString, argumentArray:[parameter])
?
Related
I would like to use a variable inside a Firestore reference. I have a sub-collections stored on the database per shop and they all have the format 'menu Shop1' or 'menu Shop2'. I have to store it this way otherwise if I use menu alone, the collectionGroup reference points to all the menus and returns them all at once - which is not what I want.
I'm struggling to pass the name of the shop to the collectionGroup reference.
This does not work:
let shopName = String("Shop1")
let collectionRef = String("menu \(shopName!)")
let ref = db.collectionGroup((collectionRef!))
But then this works:
let ref = db.collectionGroup("menu Shop1")
I have tried all the variations I know and it still wont pass the string. Does anybody know how to fix this? I'm guessing its a small tweek!
I would just concatenate the string like so:
let shopName: String = "Shop1"
let refString: String = "menu " + shopName
let ref = db.collectionGroup(refString)
Don't forget the 'space' after "menu"
You could also simplify further like so:
let shopName: String = "Shop1"
let ref = db.collectionGroup("menu " + shopName)
The argument does not need to be hard coded...
There's no need for specifying 'String'
let shopName = String("Shop1")
Just make it
let shopName = "Shop1"
Then this is not correct if the intention is to actually create a ref to a collection
let collectionRef = String("menu \(shopName!)")
it should be
let shopsCollection = db.collection("shops")
or like this
let shopName = "shop1"
let thisShop = "menu " + shopName
let shopsCollectionGroup = db.collectionGroup(thisShop)
But... I am not sure you're using the collectionGroups correctly to start with based on the names you're using.
A collection group consists of all collections with the same ID, so for example you could have a collection group of 'shops' whereas yours is called 'menu Shop1' which would indicate a single shop. Or from the guide a collectionGroup called 'landmarks' which would include landmarks from multiple cities.
Read though the Collection Group Queries guide again to ensure it's being used correctly.
As a side note, please protect your code by handling optionals properly.
shopName!
is bad news is shopName is nil as it will crash you code. See nil-coelescing operators, guard and if statements.
I have received the following string:
{"records":[{"id":"rec4haaOncoQniu8U","fields":{"orders1":5},"createdTime":"2020-02-08T09:08:22.000Z"}]}
I am not understanding how I can process and separate the values of the json in mql4 using the "JAson.mqh " library, located here: https://www.mql5.com/en/code/13663
I need the values of "orders" located under "fields" , value = 5.
the only "KEYS" that changes are the keys within the "fields" values.
i would like to be able to get the values with something like this:
string value1 = Result[0].["fields"].["orders1"]; //5
string value2 = Result[0].["fields"].["orders2"];
Please let me know what I can do.
You can get the value using the following format. Note that it has to be casted to a type. (I have casted it to int as it is the type it is in the JSON, but you can cast it to string as well)
int value1 = json["records"][0]["fields"]["orders1"].ToInt(); // if you want to make it a string use ToStr() instead of ToInt()
Here is a full example of what I did
string jsonString = "{\"records\": [{\"id\": \"rec4haaOncoQniu8U\",\"fields\": {\"orders1\": 5 }\"createdTime\": \"2020-02-08T09:08:22.000Z\"}]}";
if(json.Deserialize(jsonString))
Alert(json["records"][0]["fields"]["orders1"].ToInt());
Hope it helped.
i wrote code to get character when user enter in text field and do math with them
this :
#IBOutlet weak internal var textMeli: UITextField!
var myChar = textMeli.text
var numb = [myChar[0]*3 , myChar[1]*7]
but one is wrong
textMeli.text is a String.
myChar is a String.
You can't access a Character from a String using bracket notation.
Take a look at the documentation for the String structure.
You'll see that you can access the string's characters through the characters property. This will return a collection of Characters. Initalize a new array with the collection and you can then use bracket notation.
let string = "Foo"
let character = Array(string.characters)[0]
character will be of type Character.
You'll then need to convert the Character to some sort of number type (Float, Int, Double, etc.) to use multiplication.
Type is important in programming. Make sure you are keeping track so you know what function and properties you can use.
Off the soap box. It looks like your trying to take a string and convert it into a number. I would skip the steps of using characters. Have two text fields, one to accept the first number (as a String) and the other to accept the second number (as a String). Use a number formatter to convert your string to a number. A number formatter will return you an NSNumber. Checking out the documentation and you'll see that you can "convert" the NSNumber to any number type you want. Then you can use multiplication.
Something like this:
let firstNumberTextField: UITextField!
let secondNumberTextField: UITextField!
let numberFormatter = NumberFormatter()
let firstNumber = numberFormatter.number(from: firstNumberTextField.text!)
let secondNumber = numberFormatter.number(from: secondNumberTextField.text!)
let firstInt = firstNumber.integerValue //or whatever type of number you need
let secondInt = secondNumber.integerValue
let product = firstInt * secondInt
Dealing with Swift strings is kind of tricky because of the way they deal with Unicode and "grapheme clusters". You can't index into String objects using array syntax like that.
Swift also doesn't treat characters as interchangeable with 8 bit ints like C does, so you can't do math on characters like you're trying to do. You have to take a String and cast it to an Int type.
You could create an extension to the String class that WOULD let you use integer subscripts of strings:
extension String {
subscript (index: Int) -> String {
let first = self.startIndex
let startIndex = self.index(first, offsetBy: index)
let nextIndex = self.index(first, offsetBy: index + 1)
return self[startIndex ..< nextIndex]
}
}
And then:
let inputString = textMeli.text
let firstVal = Int(inputString[0])
let secondVal = Int(inputString[2])
and
let result = firstVal * 3 + secondVal * 7
Note that the subscript extension above is inefficient and would be a bad way to do any sort of "heavy lifting" string parsing. Each use of square bracket indexing has as bad as O(n) performance, meaning that traversing an entire string would give nearly O(n^2) performance, which is very bad.
The code above also lacks range checking or error handling. It will crash if you pass it a subscript out of range.
Note that its very strange to take multiple characters as input, then do math on the individual characters as if they are separate values. This seems like really bad user interface.
Why don't you step back from the details and tell us what you are trying to do at a higher level?
Lots of details on this throughout SO and online. Unfortunately, I cannot get any of it to work to with my string. I have this string
https://maps.googleapis.com/maps/api/directions/json?origin=%#,%#&destination=%#,%#&sensor=false&units=metric&mode=driving
And all I'm trying to do is insert the necessary values into the string by doing
let url = String(format: Constants.GoogleDirectionsUrl, road.FromCoordinates.Latitude, road.FromCoordinates.Longitude, road.ToCoordinates.Latitude, road.ToCoordinates.Longitude)
The string though always prints out as
https://maps.googleapis.com/maps/api/directions/json?origin=(null),(null)&destination=(null),(null)&sensor=false&units=metric&mode=driving
Although all the coordinates are valid. When I do string interpolation I get the correct value to show up
print("coord -- \(road.FromCoordinates.Latitude)")
coord -- 29.613929
I've tried %l, %f and %# in the string all with the same results. Anyone see what it is I'm doing incorrect here?
Update
For anyone else, here is what I ended up doing to overcome the above. I followed the answer below a bit and created a class func that I have in one of the global classes in the app. This allows me to call it from any where. Here is the function
class func createUrlDrivingDiretions (sLat: Double, sLon: Double, eLat: Double, eLon: Double) -> String {
return "https://maps.googleapis.com/maps/api/directions/json?origin=\(sLat),\(sLon)&destination=\(eLat),\(eLon)&sensor=false&units=metric&mode=driving"
}
Why don't you use the following syntax (use Swift... not legacy obj-c coding):
let var1 = "xxx"
let var2 = "yyy"
let var3 = "zzz"
let var4 = "www"
let var5 = "kkk"
let s = "https://maps.googleapis.com/maps/api/directions/json?origin=\(var1),\(var2)&destination=\(var4),\(var5)&sensor=false&units=metric&mode=driving"
Make sure var1... var5 are not optional otherwise you have to unwrap them or you'll get something like this in the output string: Optional(xxx)... instead of xxx
If you need special formatting use NumberFormatter (see this: Formatters)
I am not getting the expected result from this F# code. I would expect t to contain values as a result of the call to JsonSchema.Parse(json) but instead it is empty. What am I doing wrong?
open Newtonsoft.Json
open Newtonsoft.Json.Schema
let json = """{
"Name": "Bad Boys",
"ReleaseDate": "1995-4-7T00:00:00",
"Genres": [
"Action",
"Comedy"
]
}"""
[<EntryPoint>]
let main argv =
let t = JsonSchema.Parse(json)
0 // return an integer exit code
As John Palmer points out, JsonSchema.Parse parses a JSON schema, but from your question, it looks as though you want to parse a normal JSON value. This is possible with JsonConvert.DeserializeObject:
let t = JsonConvert.DeserializeObject json
However, the signature of DeserializeObject is to return obj, so that doesn't particularly help you access the values. In order to do so, you must cast the return value to JObject:
let t = (JsonConvert.DeserializeObject json) :?> Newtonsoft.Json.Linq.JObject
let name = t.Value<string> "Name"
Json.NET is designed to take advantage of C#'s dynamic keyword, but the exact equivalent of that isn't built into F#. However, you can get a similar syntax via FSharp.Dynamic:
open EkonBenefits.FSharp.Dynamic
let t = JsonConvert.DeserializeObject json
let name = t?Name
Notice the ? before Name. Keep in mind that JSON is case-sensitive.
Now, name still isn't a string, but rather a JValue object, but you can get the string value by calling ToString() on it, but you can also use JValue's Value property, which can be handy if the value is a number instead of a string:
let jsonWithNumber = """{ "number" : 42 }"""
let t = JsonConvert.DeserializeObject jsonWithNumber
let actual = t?number?Value
Assert.Equal(42L, actual)
I recommend to use Json type provider instead.