swift 2 get integer value from unwrap variable - ios

let g : String? = self.EKOMemberShipss[0].SUB_TYP_Price
let x:Int? = Int(g!)
self.valuePla.text = "\(x)"
Result
g String? " Optional(50)"
x Int? nil None
I just want to get x = 50

Check both the SUB_TYP_Price and the ability to be converted to Int
On success the optional is unwrapped respectively
if let g = self.EKOMemberShipss[0].SUB_TYP_Price, x = Int(g) {
self.valuePla.text = "\(x)"
}
Edit: According the screenshotSUB_TYP_Price is already String? so the downcast is not needed.

Just do something like this and it should work. (of course change the let g to whatever you want, this is just an example)
let g:String? = Optional("50")
print(g) //returns "Optional(50)"
let c = g!
print(c) //returns "50"

Related

Equation solver/parser

I have an app that solves physics problems based on given knowns and unknowns .. but it does it the wrong way..
let's say we have this equation ( d = v * t )
We have here three variables .. the way I did it is like this
let v = 10
let t = 5
let d = nil
let result = Double()
if d == nil && v != nil && t != nil {
result = v * t
}if v == nil && d != nil && t != nil {
result = d / t
}if t == nil && v != nil && d != nil {
result = d / v
}else{
result = nil
}
print(result) // "50"
obviously it's a headache .. this is only a small equation with three vars.. what if I had 20 equations each has 5 vars.. it would be very exhausting to type.. So I'm wondering if there is a way to just type the equation and call .solve or something .. something like this
let equation = "d = v * t"
let knowns = [d:20,v:50]
let result = equation.solve(usingKnowns: knowns)
print(result) // "Optional(t = 0.4)"
Thanks in advance,
Any help would be really great
The problem here is to see what variable is unknown, supose you have X variables and you always get X-1 variables known and 1 unknown you don't really need to check if the knowns variables are != nil.
Other possibility is the one I recommend you:
func resolve(a: Double?, b: Double?, c: Double?)-> Double{
//Default value
var result: Double = 0.0
//a missing
if let b = b, let c = c{
result = b*c
}
//b missing
if let a = a, let b = b{
result = a/b
}
//c missing
if let a = a, let c = c{
result = a/c
}
return result
}
In this case you have a single call with the 3 parameters, all of them optionals, so if you try a "if let" with 2 o them simultaneously and it works, it means the other one is the unknow variable.
This is the "cleanest" solution I can think of.

Swift search value for the nearest similar value reagrdless of sequence

Hi guys I want to ask how do you search the items for the nearest possible similar value regarding of the sequence. Example as below when I search for ["Restaurant","Bull"], it should return me str2 is the possible nearest values. Because this function only able to work for order sequence, it cannot for non-sequence. I really hope you guys can help me out....
func search(`for` searchItems: Set<String>, `in` searchArea: [Set<String>]) -> Set<String>? {
return searchArea.max(by: { (a, b) -> Bool in
return searchItems.intersection(a).count < searchItems.intersection(b).count || searchItems.intersection(a).count > searchItems.intersection(b).count
})
}
let str2: Set<String> = ["Bull","Restaurant","Corner"]
let str3: Set<String> = ["Corner","Restaurant","Mole"]
let area = [str3, str2] as [Any]
print("search result",self.search(for: ["Restaurant","Bull"], in: area as! [Set<String>]))
Probably because your str2 and str3 is not Set at all, it's array coz you are using array declaration, thus change it to this then it works if you use ["Bull", "Restaurant"]:
let str2 = Set(["Bull","Restaurant","Corner"])
let str3 = Set(["Corner","Restaurant","Mole"])
Also, Set is non-ordered sequence, Array is ordered sequence
Just make a set out of your query array and use its isSubset(of:) method to check wether it's a subset of your data.
let set1 = Set([1,2,3])
let set2 = Set([2,3,4])
let query = [1,2]
let querySet = Set(query)
querySet.isSubset(of: set1) // true
querySet.isSubset(of: set2) // false
let query2 = [2,1]
let querySet2 = Set(query)
querySet2.isSubset(of: set1) // true
querySet2.isSubset(of: set2) // false

Indexes as Ints in Swift

I have the following code which I've commented:
func hash (s:String) -> Int {
var z = 19
let key = "abcdefghijk"
for var i = 0; i < s.characters.count; i++ {
let index = s.startIndex.advancedBy(i)
let char = s[index]
if let f = key.characters.indexOf(char) {
print(f) //This outputs the number I want to use in the next line, but as String.CharacterView.Index, not an Int
z = (z * f) //obviously this won't work
}
// So instead we try this:
z = z * s.startIndex.distanceTo(key.characters.indexOf(char)!))
// It works for the first few characters then I get "fatal error: can not increment endIndex" and a EXC_BAD_INSTRUCTION
}
return z
}
I'm struggling to use Swift String to find the index I want to use as an Int in some kind of a hash function. In case it isn't clear:
User inputs a string, the function iterates through each character, finding that character in the key and then takes the index of that character in key and multiplies it to the existing z counter.
I get the results I want but only in the wrong type which doesn't let me convert to Int. Anyone know how?
Thanks
f = key.characters.indexOf(char) is an index into the characters
of key, therefore you have to compute the distance to the start index of key, not s:
z = z * key.startIndex.distanceTo(key.characters.indexOf(char)!))
which you can move back to your if-let block:
if let f = key.characters.indexOf(char) {
z = z * key.startIndex.distanceTo(f)
}
You also might want to use the overflow operator &*
if let f = key.characters.indexOf(char) {
z = z &* key.startIndex.distanceTo(f)
}
otherwise the application will crash if the result of the
multiplication does not fit into an Int.
Generally, the indexes of a Swift String can only be used
with the same string (regardless of string length), as the following
example demonstrates:
let s1 = "abc"
let i1 = s1.characters.indexOf("b")!
print(i1) // 1
let s2 = "🇩🇪a🇩🇪b🇩🇪c"
print(s2.characters.count) // 6
let d2 = s2.startIndex.distanceTo(i1) // fatal error: can not increment endIndex
If you make your key into an array of Characters, then indexOf will return the Int you need:
func hash (s:String) -> Int {
var z = 19
let key = Array("abcdefghijk".characters)
for char in s.characters {
if let f = key.indexOf(char) {
print(f)
z = (z &* (f + 1))
}
}
return z
}
Also, if your character is the first index in the key you will get a value of 0 which will make your hash value 0, so I've added 1 to f. I also incorporated &* as suggested by #MartinR to prevent Int overflow.
First, don't use forced unwrap as you can end up easily crashing your app (as it seems it already happened).
Second, you already test for the validity of key.characters.indexOf(char), you can place the z computation within the if-let:
z = z * s.startIndex.distanceTo(f)
What happens with your code is that the hash() function crashes as soon as it encounters a character beyond k, so you should also add all possible characters to key.

String componentsSeparatedByString do one time

I have a string:
let mystring = "key=value=value=value=value"
When i did:
let ar = mystring.componentsSeparatedByString("=")
i get:
["key", "value", "value", "value", "value"]
but i need do split only once, like componentsSeparatedByString("=", 1), to get:
["key", "value=value=value=value"]
With Swift 2.1, you can use the split function as follows to do what you want:
let result = string.characters.split("=", maxSplit: 1, allowEmptySlices: true)
Some example code to test this would be:
let string = "key=value=value=value=value"
let result = string.characters.split("=", maxSplit: 1, allowEmptySlices: true)
print(String(result[0])) // "key"
print(String(result[1])) // "value=value=value=value"
This should do the job
func extract(rawData: String) -> [String]? {
let elms = rawData.characters.split("=", maxSplit: 1).map { String($0) }
guard let
key = elms.first,
value = elms.last
where elms.count == 2 else { return nil }
return [key, value]
}
Example:
let rawData = "key=value=value=value=value"
extract(rawData) // > ["key", "value=value=value=value"]
Please note the extract function does an optional array of strings. Infact if the input string does not contain at least an = then nil is returned.
The code has been tested with the Swift 2.1 and Xcode Playground 7.1.1.
Hope this helps.
You're probably going to have to write your own custom code to do that, using either NSScanner or rangeofString:options:range:
EDIT:
Actually, it sounds like the Swift String class's split function, with its maxSplit parameter, will do what you need. Take a look at the link in Preston's answer.
let mystring = "key=value=value=value=value"
let result = split(mystring as String, { $0 == "=" }, maxSplit: 1, allowEmptySlices: true)
result should now be [key, value=value=value=value]
Thanks for answers, i found working solution for swift2:
let mystring = "key=value=value=value=value"
mystring.characters.split(1, allowEmptySlices: true, isSeparator: { $0 == "=" }).map(String.init)
Try this: (tested and working in playground)
var key = str.substringToIndex(str.rangeOfString("=")!.startIndex)
var value = str.substringFromIndex(str.rangeOfString("=")!.startIndex.advancedBy(1))
var resultingArray = [key, value]

What is the difference between " as string" and "stringvalue" in swift?

I have a code :
var i : AnyObject!
i = 10
println(i as String)
println(i.stringValue)
it get crashed on as String line but runs in second i.stringValue.
What is the difference between as String and stringValue in the above lines?
.stringValue is a way to extract Integer into string value but as String will not work for that And if you use as String then Xcode will force you to add ! with as which is not good and it will never succeed and it would crash your app. you can't cast Int to String. It will always fail. Thats why when you do as! String it crashes the app.
So casting is not a good idea here.
And here is some more ways to extract Integer into string value:
let i : Int = 5 // 5
let firstWay = i.description // "5"
let anotherWay = "\(i)" // "5"
let thirdWay = String(i) // "5"
Here you can not use let forthway = i.stringValue because Int Doesn't have member named stringValue
But you can do same thing with anyObject as shown below:
let i : AnyObject = 5 // 5
let firstWay = i.description // "5"
let anotherWay = "\(i)" // "5"
let thirdWay = String(i) // "5"
let forthway = i.stringValue // "5" // now this will work.
Both are casting an Int to String but this will not work anymore.
In Swift 2 its not possible to do it like that.
U should use:
let i = 5
print(String(format: "%i", i))
This will specifically write the int value as a String
with as String, you can not cast the value but you define that the variable contains String but in you case it is Int.so it crashes.
while the other way i.e. of i.stringValue cast your value into String.So it doesn't gives you any crash and successfully cast into String value.
Note: As you are using AnyObject, variable have member stringvalue...but Int doesn't have...To cast Int value check out #Dharmesh Kheni answer

Resources